import requests, uuid, urllib.parse, os, json, base64, re, time, math
from dateutil.relativedelta import relativedelta
from Administrative_office_system.settings import post_url
from administrative.utils import send_mssage
from administrative.views import unagree_official
from back_management.models import topic_meeting
from personal_center.process_check import hanzi_to_pinyin
from finance.models import SealMaking, QuickAuthorization, \
    QuickAuthorizationApplicationCategory, LogisticsOffice, MedicalMaterials, NutritionalMeals, SubjectFunding, \
    LaborUnionExpenses, GeneralFinance, BookSubscription, TravelApply, TravelReimbursement, OutgoingCadresData, \
    Dimission, BusinessContract, NewMedicalServices, SurgicalGrading, \
    SoloPracticeApply, PartyBuilding, ResearchFunding, LeaveRequest, LeaveRequestTypeDays, ObjectAudit
from medical_ethics.models import EvaluationOfMedicalEthics, EvaluationOpinion
from ios_api import sql_file
from django.db import connection
from django.db.models import Q, Count
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from Oa_system.models import Staffing
from administrative.models import VehicleApply, VehicleAuditRecord, VehicleUseInfo, Vehicle, Driver, Company, Topics, \
    TopicsAuditRecord, Topicsattachments, ConferenceMemo, ConferenceMemoAuditRecord, OfficialDocumentsAuditRecord, \
    OfficialDocuments, PublicSearch, Correspondence, CorrespondenceRecord, CorrespondencePeople, ConferenceMemoPeople, \
    OfficialDocumentsPeople, PaymentApproval, ContractApproval
from Administrative_office_system.utils.views import LoginRequiredMixin
from announcements.models import NoticePeople, AuditRecord, Notice
from correspondence.models import InboxInfoPeople, InboxInfo, chatting_records
from personal_center.models import User, Group, SortLine, ConferenceRoomApplication, SealApply, \
    SealApplyAuditRecord, MakeCopy, seal, SealApplyNumber, FixedAssets
from datetime import datetime, timedelta
# Create your views here.
from personal_center.process_check import my_shouwen
# 首页轮播图
from personal_center.views import num_to_char
from logistics.models import *
from logistics.MessagePushOperationRecords import RecordAndPush



class GetAllStaffApi(LoginRequiredMixin, View):
    def post(self, request):
        returnDict, return_list, department_list = {}, [], []
        branch_list = Company.objects.all()
        group_list = []
        people_dict_new_list = []

        groups = Group.objects.all()
        for group in groups:
            temp_list = []
            people_dict_new = {}
            for user_objs in group.user_set.all():
                temp_list.append({
                    'real_name': user_objs.real_name,
                    'job_number': user_objs.job_number
                })
            people_dict_new['department'] = group.level
            people_dict_new['users'] = temp_list
            people_dict_new_list.append(people_dict_new)
            group_list.append(group.level)
        emp_info_list = []
        for i in branch_list:
            emp_info_dict = {}
            return_list.append(i.name)
            one_data = i.user_set.filter(is_delete=0)
            if len(one_data) == 0:
                continue
            emp_info = []
            for dat in one_data:
                emp_info.append({
                    'real_name': dat.real_name,
                    'job_number': dat.job_number
                })
            emp_info_dict['department'] = i.name
            emp_info_dict['users'] = emp_info
            emp_info_list.append(emp_info_dict)
        returnDict = {'code': 200, 'message': 'success', 'emp_info_dict': emp_info_list, 'people_dict_new': people_dict_new_list, 'branch_list': return_list, 'group_list': group_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GetUserInfoApi(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        menu_list = []
        bill_dict = {}
        group = user.group
        billgroup_objs = group.billgroup_set.filter(type='app')
        executor_billgroup_objs = user.billgroup_set.filter(type='app')
        for billgroup_obj in billgroup_objs:
            if billgroup_obj.menu in bill_dict:
                bill_dict[billgroup_obj.menu].append(billgroup_obj.bill)
            else:
                bill_dict[billgroup_obj.menu] = [billgroup_obj.bill]

        for billgroup_obj in executor_billgroup_objs:
            if billgroup_obj.menu in bill_dict:
                if billgroup_obj.bill not in bill_dict[billgroup_obj.menu]:
                    bill_dict[billgroup_obj.menu].append(billgroup_obj.bill)
            else:
                bill_dict[billgroup_obj.menu] = [billgroup_obj.bill]

        # print(bill_dict)
        temp_list = []
        gw_dict = {}
        for k, v in bill_dict.items():
            if k in ('内部发文', '上级来文'):
                gw_dict['items'] = '公文管理'
                if 'infos' not in gw_dict:
                    gw_dict['infos'] = [{'menu': k, 'bill': v}]
                else:
                    gw_dict['infos'].append({'menu': k, 'bill': v})
            else:
                temp_dict = {'menu': k, 'bill': v}
                temp_list.append(temp_dict)
        if len(gw_dict):
            temp_list.insert(0, gw_dict)
        # print('temp_list', temp_list)
        # print('gw_dict', gw_dict)
        leaders = [{'id': request.user.company.leaders_id.id, 'name': request.user.company.leaders_id.real_name}]
        if request.user.company.id in (3, 80):
            com_objs = Company.objects.filter(id__in=[3, 80])
            leaders = [{'id': record.leaders_id.id, 'name': record.leaders_id.real_name} for record in com_objs]

        info_dict = {
            'name': user.real_name,
            'gender': user.get_gender_display(),
            'department': user.department,
            'education': user.first_degree,
            'position': user.position,
            'mailbox': user.mailbox,
            'mobile': user.mobile,
            'role': user.role,
            'temp_list': temp_list,
            'head_portrait': '/media/' + str(user.head_portrait) if user.head_portrait else '',
            'group': user.group.level,
            'leaders': leaders
        }
        returnDict = {'code': 200, 'message': 'success', 'info_dict': info_dict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GetAllCompanyApi(LoginRequiredMixin, View):
    def post(self, request):
        company_list = [{'item_id': c.id, 'value': c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
        returnDict = {'code': 200, 'message': '获取成功', 'company_list': company_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TopicsDataApi(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        sql = """ SELECT COUNT(date_format(create_time,'%%Y-%%m-%%d')) as count, date_format(create_time,'%%Y-%%m-%%d') as date 
                        from administrative_topics 
                        where create_time >= %(statr_time)s and create_time <= %(end_time)s 
                        GROUP BY date_format(create_time,'%%Y-%%m-%%d') """
        sql2 = """ SELECT COUNT(date_format(create_time,'%%Y-%%m')) as count, date_format(create_time,'%%Y-%%m') as date 
                                            from administrative_topics 
                                            where create_time >= %(statr_time)s and create_time <= %(end_time)s 
                                            GROUP BY date_format(create_time,'%%Y-%%m') """
        start_date = (datetime.now() + timedelta(days=-30)).strftime("%Y-%m-%d")
        end_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        three_month_before = (datetime.now() - relativedelta(months=3)).strftime("%Y-%m-%d")
        six_month_before = (datetime.now() - relativedelta(months=6)).strftime("%Y-%m-%d")
        year_before = (datetime.now() - relativedelta(months=12)).strftime("%Y-%m-%d")
        print(three_month_before)
        one_month_list = []
        three_month_list = []
        six_month_list = []
        year_list = []
        one_month_dict = {}
        three_month_dict = {}
        six_month_dict = {}
        year_dict = {}
        for i in range(0, 31):
            temp_date = (datetime.now() + timedelta(days=-i)).strftime("%Y-%m-%d")
            one_month_dict[temp_date] = 0
        for i in range(0, 3):
            temp_date = (datetime.now() - relativedelta(months=i)).strftime("%Y-%m")
            three_month_dict[temp_date] = 0
        for i in range(0, 6):
            temp_date = (datetime.now() - relativedelta(months=i)).strftime("%Y-%m")
            six_month_dict[temp_date] = 0
        for i in range(0, 12):
            temp_date = (datetime.now() - relativedelta(months=i)).strftime("%Y-%m")
            year_dict[temp_date] = 0

        with connection.cursor() as cursor:
            # print(sql%{"statr_time": start_date, "end_time": end_date})
            cursor.execute(sql, {"statr_time": start_date, "end_time": end_date})
            rows1 = cursor.fetchall()
            for row in rows1:
                # one_month_list.append({'count': row[0], 'date': row[1]})
                one_month_dict[row[1]] = row[0]
            for k, v in one_month_dict.items():
                one_month_list.append({'date': k, 'count': v})

            cursor.execute(sql2, {"statr_time": three_month_before, "end_time": end_date})
            rows2 = cursor.fetchall()
            for row in rows2:
                three_month_dict[row[1]] = row[0]
            for k, v in three_month_dict.items():
                three_month_list.append({'date': k, 'count': v})
                # three_month_list.append({'count': row[0], 'date': row[1]})

            cursor.execute(sql2, {"statr_time": six_month_before, "end_time": end_date})
            rows3 = cursor.fetchall()
            for row in rows3:
                six_month_dict[row[1]] = row[0]
            for k, v in six_month_dict.items():
                six_month_list.append({'date': k, 'count': v})
                # six_month_list.append({'count': row[0], 'date': row[1]})

            cursor.execute(sql2, {"statr_time": year_before, "end_time": end_date})
            rows4 = cursor.fetchall()
            for row in rows4:
                year_dict[row[1]] = row[0]
            for k, v in year_dict.items():
                year_list.append({'date': k, 'count': v})
                # year_list.append({'count': row[0], 'date': row[1]})

        print('one_month_dict', one_month_dict)

        returnDict = {'code': 200, 'message': '获取成功', 'one_month_list': one_month_list,
                      'three_month_list': three_month_list, 'six_month_list': six_month_list, 'year_list': year_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class WriteUserInfoApi(LoginRequiredMixin, View):
    def post(self, request):
        user = request.user
        education = request.POST.get('education', None)
        department = request.POST.get('department', None)
        position = request.POST.get('position', None)
        mailbox = request.POST.get('mailbox', None)
        mobile = request.POST.get('mobile', None)
        role = request.POST.get('role', None)
        if education:
            user.education = education
        if department:
            user.department = department
        if position:
            user.position = position
        if mailbox:
            user.mailbox = mailbox
        if mobile:
            user.mobile = mobile
        if role:
            user.role = role
        user.save()
        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 车辆接口
class VehicleApplyIndexApi(LoginRequiredMixin, View):
    def get(self, request):
        objs = User.objects.filter(group__in=[1, 2])
        data = ['%s(%s)' % (obj.real_name, obj.job_number) for obj in objs]
        returnDict = {'code': 200, 'message': 'success', 'data': data}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        user = request.user
        subject = request.POST.get('subject', None)
        route = request.POST.get('route', None)
        travelers_users = request.POST.get('travelers_users', '')
        start_time = request.POST.get('start_time', None)
        end_time = request.POST.get('end_time', None)
        is_fix = request.POST.get('is_fix', None)
        field_leader = request.POST.get('field_leader', None)
        print(subject, route, travelers_users, start_time, end_time, is_fix)
        if not subject or not route or not start_time or not end_time or not is_fix:
            returnDict = {'code': 500, 'message': '缺少必填参数'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') > datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S'):
            returnDict = {'code': 500, 'message': '预定开始日期大于预定结束日期'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if is_fix == '否' and (datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') < datetime.now()):
            returnDict = {'code': 500, 'message': '非补录单据不能选择今天之前的日期'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        try:
            if travelers_users:
                travelers_users = re.findall('\((.*?)\)', travelers_users)
                field_leader_numbers = re.findall('\((.*?)\)', field_leader)
                start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                v = VehicleApply.objects.create(subject=subject, route=route,
                                                travelers_numbers=', '.join(travelers_users),
                                                field_leader_numbers=', '.join(field_leader_numbers),
                                                start_time=start_time, end_time=end_time,
                                                is_fix=True if is_fix == '是' else False, apply_user=request.user,
                                                current_audit_user=User.objects.get(
                                                    real_name=user.company.leaders))
                temp_list = v.travelers_numbers.split(', ')
                travelers_users_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in
                                        temp_list]
                travelers_users_str = ', '.join(travelers_users_list)
                v.travelers_names = travelers_users_str
            else:
                field_leader_numbers = re.findall('\((.*?)\)', field_leader)
                start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                v = VehicleApply.objects.create(subject=subject, route=route,
                                                travelers_numbers=', '.join(travelers_users),
                                                field_leader_numbers=', '.join(field_leader_numbers),
                                                start_time=start_time, end_time=end_time,
                                                is_fix=True if is_fix == '是' else False, apply_user=request.user,
                                                current_audit_user=User.objects.get(
                                                    real_name=user.company.leaders))

            temp_list1 = v.field_leader_numbers.split(', ')
            field_leader_users_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in
                                       temp_list1]
            field_leader_str = ', '.join(field_leader_users_list)
            v.field_leader = field_leader_str
            com = Company.objects.get(abbreviation='CD')
            cd_user_obj = User.objects.get(real_name=com.director)
            v.save()
            VehicleAuditRecord.objects.create(notice_id=v, state='unaudit',
                                              audit_people=User.objects.get(real_name=user.company.leaders),
                                              audit_note='', node='B')
            VehicleAuditRecord.objects.create(notice_id=v, state='unaudit',
                                              audit_people=cd_user_obj, audit_note='', node='YB')
            VehicleAuditRecord.objects.create(notice_id=v, state='unaudit',
                                              audit_people=User.objects.get(job_number='8008'), audit_note='',
                                              node='CGB')
            # 将数据插入公共表
            content = {'id': v.id, 'subject': v.subject, 'route': v.route}
            public_search_obj = PublicSearch.objects.create(type='a', content=json.dumps(content, ensure_ascii=False),
                                                            apply_people=v.apply_user, state=v.state)
            public_search_obj.current_audit_users.add(User.objects.get(real_name=user.company.leaders))
            v.public_search = public_search_obj
            v.save()
            returnDict = {'code': 200, 'message': 'success'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        except Exception as e:
            if v:
                v.delete()
            print(e)
            returnDict = {'code': 500, 'message': '创建失败!'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class VehicleApplyListApi(LoginRequiredMixin, View):
    def get(self, request):
        page = request.GET.get('page', 1)
        ready_objs = request.user.vehicle_apply_current_audit_user.all().order_by("-create_time")[
                     (int(page) - 1) * 20:int(page) * 20]
        already_objs = request.user.vehicle_apply_already_users.all().order_by("-create_time")[
                       (int(page) - 1) * 20:int(page) * 20]
        ready_list = [{'apply_user': v_obj.apply_user.real_name, 'subject': v_obj.subject, 'route': v_obj.route,  # 车辆待办
                       'state': v_obj.get_state_display(), 'id': v_obj.id,
                       'audit_user': v_obj.current_audit_user.real_name,
                       'start_time': v_obj.start_time.strftime("%Y-%m-%d %H:%M"),
                       'end_time': v_obj.end_time.strftime("%Y-%m-%d %H:%M")} for v_obj in ready_objs]
        already_list = [
            {'apply_user': v_obj.apply_user.real_name, 'subject': v_obj.subject, 'route': v_obj.route,  # 车辆已办
             'state': v_obj.get_state_display(), 'id': v_obj.id,
             'audit_user': v_obj.current_audit_user.real_name if v_obj.current_audit_user else '',
             'start_time': v_obj.start_time.strftime("%Y-%m-%d %H:%M"),
             'end_time': v_obj.end_time.strftime("%Y-%m-%d %H:%M")} for v_obj in already_objs]
        returnDict = {'code': 200, 'message': 'success', 'ready_list': ready_list,
                      'already_list': already_list,
                      }
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class VehicleApplyDetailApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        try:
            v_obj = VehicleApply.objects.get(id=int(id))
        except:
            returnDict = {'code': 500, 'message': 'success'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            vehicle_use_infos = VehicleUseInfo.objects.filter(
                Q(start_time__range=[v_obj.start_time, v_obj.end_time]) | Q(
                    end_time__range=[v_obj.start_time, v_obj.end_time]))
            used_vehicle_list = [vehicle_use_info.vehicle for vehicle_use_info in vehicle_use_infos]
            vehicle_objs = Vehicle.objects.all()
            vehicle_list = [vehicle_obj for vehicle_obj in vehicle_objs if vehicle_obj not in used_vehicle_list]
            vehicle_list = [{'number': temp.registration_number} for temp in vehicle_list]

            used_driver_list = [vehicle_use_info.driver for vehicle_use_info in vehicle_use_infos]
            driver_objs = Driver.objects.all()

            driver_list = [{'name': temp.name} for temp in driver_objs if temp.name not in used_driver_list]
            audit_dic = {}
            for audit_obj in v_obj.vehicleauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.get_state_display(),
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state': audit_obj.get_state_display(),
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            travelers_names = v_obj.travelers_names.split(', ')
            travelers_numbers = v_obj.travelers_numbers.split(', ')
            temp_list = []
            for travelers_name in travelers_names:
                temp_list.append('%s(%s)' % (travelers_name, travelers_numbers[travelers_names.index(travelers_name)]))
            # print(temp_list)
            temp_travelers = ', '.join(temp_list)

            field_leader_names = v_obj.field_leader.split(', ')
            field_leader_numbers = v_obj.field_leader_numbers.split(', ')
            field_leader_list = []
            for field_leader_name in field_leader_names:
                field_leader_list.append(
                    '%s(%s)' % (field_leader_name, field_leader_numbers[field_leader_names.index(field_leader_name)]))
            temp_field_leader = ', '.join(field_leader_list)

            data_dic = {'apply_user': v_obj.apply_user.real_name,
                        "department": v_obj.apply_user.department,
                        'state': v_obj.state,
                        'id': v_obj.id,
                        'subject': v_obj.subject,
                        'route': v_obj.route,
                        'is_audit': 'true' if v_obj.state != 'refuse' and v_obj.current_audit_user == request.user else 'false',
                        'travelers_names': v_obj.travelers_names,
                        'field_leader': temp_field_leader,
                        'temp_travelers': temp_travelers,
                        'is_fix': v_obj.is_fix,
                        'vehicles': v_obj.vehicles,
                        'drivers': v_obj.drivers,
                        'start_time': v_obj.start_time.strftime("%Y-%m-%d %H:%M"),
                        'end_time': v_obj.end_time.strftime("%Y-%m-%d %H:%M"),
                        'vehicle_list': vehicle_list,
                        'driver_list': driver_list,
                        'audit_list': audit_dic
                        }
            returnDict = {'code': 200, 'message': 'success', 'data': data_dic}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        vehicles = request.POST.get('vehicles', None)
        drivers = request.POST.get('drivers', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        RecordAndPush().OperationRecords(request, "车辆管理")
        is_cgb = False
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        try:
            va_obj = VehicleApply.objects.get(id=int(id))
            topic_type = "车辆管理"
            applicant = va_obj.apply_user.real_name
            ApplicationTime = va_obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = va_obj.subject[:15] + "……" if len(va_obj.subject) > 15 else va_obj.subject
            if va_obj.state == 'draft':
                vad_obj = VehicleAuditRecord.objects.filter(notice_id=va_obj, node='B', state='unaudit').first()
                if state == 'audit':
                    va_obj_state = 'fg'
                    com = Company.objects.get(abbreviation='CD')
                    cd_user_obj = com.head_people
                    va_obj.current_audit_user = cd_user_obj
                    try:
                        RecordAndPush().MessagePush(cd_user_obj.openid, topic_type, applicant, ApplicationTime,
                                                    SubjectMatter)
                    except:
                        pass
                else:
                    va_obj_state = 'refuse'
                    va_obj.current_audit_user = va_obj.apply_user
            elif va_obj.state == 'fg':
                vad_obj = VehicleAuditRecord.objects.filter(notice_id=va_obj, node='YB', state='unaudit').first()
                if state == 'audit':
                    va_obj_state = 'ybzr'
                    com = Company.objects.get(id=34)
                    va_obj.current_audit_user = com.leaders_id
                    try:
                        RecordAndPush().MessagePush(com.leaders_id.openid, topic_type, applicant, ApplicationTime,
                                                    SubjectMatter)
                    except:
                        pass
                    if vehicles and drivers:
                        va_obj.vehicles = vehicles
                        va_obj.drivers = drivers
                        vehicle_obj = Vehicle.objects.get(registration_number=va_obj.vehicles)
                        VehicleUseInfo.objects.create(vehicle=vehicle_obj, start_time=va_obj.start_time,
                                                      end_time=va_obj.end_time, driver=va_obj.drivers, apply_id=va_obj)
                    else:
                        returnDict = {'code': 500, 'message': '车队负责人审核需要指定车辆和司机'}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                    if va_obj.vehicleauditrecord_set.filter(
                            node='B').last().audit_people == va_obj.vehicleauditrecord_set.filter(
                            node='CGB').last().audit_people:
                        is_cgb = True

                else:
                    va_obj_state = 'refuse'
                    va_obj.current_audit_user = va_obj.apply_user
            elif va_obj.state == 'ybzr':
                vad_obj = VehicleAuditRecord.objects.filter(notice_id=va_obj, node='CGB', state='unaudit').first()
                if state == 'audit':
                    va_obj_state = 'cgb'
                    mobiles = []
                    va_obj.current_audit_user = None
                    driver = User.objects.filter(real_name=va_obj.drivers)
                    if driver:
                        mobiles.append(driver.first().mobile)

                    if not va_obj.is_fix and datetime.now() < va_obj.end_time:
                        content = '您的车辆申请已预定成功, 时间：%s-%s, 路线：%s, 同行人员(%s), 车辆(%s), 司机为%s(%s)' % (
                            va_obj.start_time.strftime("%Y-%m-%d %H:%M"), va_obj.end_time.strftime("%Y-%m-%d %H:%M"),
                            va_obj.route, va_obj.field_leader, va_obj.vehicles, va_obj.drivers,
                            User.objects.filter(real_name=va_obj.drivers).first())
                        mobiles.append(va_obj.apply_user.mobile)
                        mobiles = list(set(mobiles))
                        res = send_mssage(mobiles, content)

                else:
                    va_obj_state = 'refuse'
                    va_obj.current_audit_user = va_obj.apply_user
                    vehicle_use_infos = VehicleUseInfo.objects.filter(apply_id=va_obj)
                    for vehicle_use_info in vehicle_use_infos:
                        vehicle_use_info.delete()

            else:
                returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            va_obj.state = va_obj_state
            va_obj.save()
            vad_obj.update_time = datetime.now()
            vad_obj.state = state
            vad_obj.audit_note = audit_note
            vad_obj.save()
            if is_cgb:
                mobiles = []
                va_obj_state = 'cgb'
                va_obj.state = va_obj_state
                va_obj.current_audit_user = None
                va_obj.save()
                driver = User.objects.filter(real_name=va_obj.drivers)
                if driver:
                    mobiles.append(driver.first().mobile)
                travelers_numbers = va_obj.travelers_numbers.split(', ')
                for travelers_number in travelers_numbers:
                    user_obj = User.objects.filter(job_number=travelers_number)
                    if user_obj:
                        mobiles.append(user_obj.first().mobile)

                field_leader_numbers = va_obj.field_leader_numbers.split(', ')
                for field_leader_number in field_leader_numbers:
                    user_obj = User.objects.filter(job_number=field_leader_number)
                    if user_obj:
                        mobiles.append(user_obj.first().mobile)
                if not va_obj.is_fix and datetime.now() < va_obj.end_time:
                    content = '您的车辆申请已预定成功, 时间：%s-%s, 路线：%s, 同行人员(%s)' % (
                        va_obj.start_time.strftime("%Y-%m-%d %H:%M"), va_obj.end_time.strftime("%Y-%m-%d %H:%M"),
                        va_obj.route, va_obj.field_leader)
                    mobiles.append(va_obj.apply_user.mobile)
                    mobiles = list(set(mobiles))
                    res = send_mssage(mobiles, content)

                b_vad_obj = va_obj.vehicleauditrecord_set.filter(node='B', state='audit').last()
                vad_obj = VehicleAuditRecord.objects.filter(notice_id=va_obj, node='CGB', state='unaudit').first()
                vad_obj.update_time = datetime.now()
                vad_obj.state = 'audit'
                vad_obj.audit_note = b_vad_obj.audit_note
                vad_obj.save()

            if request.user not in va_obj.already_users.all():
                va_obj.already_users.add(request.user)
            returnDict = {'code': 200, 'message': '审核成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        except Exception as e:
            print("e: ", e)
            returnDict = {'code': 500, 'message': '审批失败请联系管理员'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class VehicleUseInfoViewApi(LoginRequiredMixin, View):
    def get(self, request):
        page = request.GET.get('page', 1)
        now_time = datetime.now().strftime("%Y-%m-%d")
        five_day_after = (datetime.now() + timedelta(days=5)).strftime("%Y-%m-%d")
        # print(now_time, five_day_after)
        vehicle_use_info = VehicleUseInfo.objects.filter(start_time__gte=now_time, end_time__lte=five_day_after)
        # print(vehicle_use_info)
        vehicle_use_info_list = [{'registration_number': v.vehicle.registration_number, 'driver': v.vehicle.driver,
                                  'start_time': v.start_time.strftime("%Y-%m-%d %H:%M"),
                                  'end_time': v.end_time.strftime("%Y-%m-%d %H:%M"),
                                  'seat': v.vehicle.seat} for v in
                                 vehicle_use_info]
        my_apply_list = [{'apply_user': v_obj.apply_user.real_name, 'subject': v_obj.subject, 'route': v_obj.route,
                          'state': v_obj.get_state_display(), 'id': v_obj.id,
                          'current_audit_user': User.objects.get(
                              id=v_obj.current_audit_user_id).real_name if v_obj.current_audit_user else '',
                          'start_time': v_obj.start_time.strftime("%Y-%m-%d %H:%M"),
                          'end_time': v_obj.end_time.strftime("%Y-%m-%d %H:%M")} for v_obj in
                         VehicleApply.objects.filter(apply_user=request.user).order_by('-start_time')[
                         (int(page) - 1) * 20:int(page) * 20]]
        returnDict = {'code': 200, 'message': '获取成功', 'vehicle_use_info_list': vehicle_use_info_list,
                      'my_apply_list': my_apply_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class VehicleApplyWriteViewApi(LoginRequiredMixin, View):
    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        subject = request.POST.get('subject', None)
        route = request.POST.get('route', None)
        travelers_users = request.POST.get('travelers_users', None)
        start_time = request.POST.get('start_time', None)
        end_time = request.POST.get('end_time', None)
        is_fix = request.POST.get('is_fix', None)

        obj = VehicleApply.objects.get(id=int(id))
        if obj.state != 'refuse':
            returnData = {'code': 500, 'message': '修改错误，只有为拒绝状态的车辆申请才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        try:
            if subject:
                obj.subject = subject
            if route:
                obj.route = route
            if start_time:
                start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
                # print(type(obj.start_time))
                obj.start_time = start_time
            if end_time:
                end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
                obj.end_time = end_time
                # print(end_time)
            if is_fix:
                obj.is_fix = True if is_fix == '是' else False
            if travelers_users:
                travelers_users = re.findall('\((.*?)\)', str(travelers_users))
                obj.travelers_numbers = ', '.join(travelers_users)
                temp_list = obj.travelers_numbers.split(', ')
                travelers_users_list = [User.objects.get(job_number=user_str.strip()).real_name for user_str in
                                        temp_list]
                travelers_users_str = ', '.join(travelers_users_list)
                obj.travelers_names = travelers_users_str

            if len(obj.vehicleauditrecord_set.filter(node='B', state='unaudit')) == 0:
                VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit',
                                                  audit_people=User.objects.get(real_name=user.company.leaders),
                                                  audit_note='', node='B')
            if len(obj.vehicleauditrecord_set.filter(node='YB', state='unaudit')) == 0:
                VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit',
                                                  audit_people=User.objects.get(job_number='8166'), audit_note='',
                                                  node='YB')
            if len(obj.vehicleauditrecord_set.filter(node='CGB', state='unaudit')) == 0:
                VehicleAuditRecord.objects.create(notice_id=obj, state='unaudit',
                                                  audit_people=User.objects.get(job_number='8008'), audit_note='',
                                                  node='CGB')
            obj.state = 'draft'
            obj.current_audit_user = User.objects.get(real_name=user.company.leaders)
            obj.save()
            returnDict = {'code': 200, 'message': '修改成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        except Exception as e:
            print(e)
            obj.state = 'refuse'
            obj.save()
            returnData = {'code': 500, 'message': '修改错误'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class VehicleApplyCancelViewApi(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = VehicleApply.objects.get(id=int(id))
        if obj.state != 'draft':
            returnData = {'code': 500, 'message': '作废失败，只有为新建状态的车辆申请才能作废！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_user = None
        obj.state = 'cancel'
        obj.save()
        returnData = {'code': 200, 'message': '成功作废！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 议题接口
class TopicsDetailViewApi(LoginRequiredMixin, View):
    def get(self, request):         # 议题详情
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except Exception as E:
            print(E)
            return redirect("/")
        view_s = request.GET.get("views", None)
        ids = request.GET.get("id", None)
        flag = ""
        if view_s:
            flag = True
        revocation_flag = 'true'  # 撤回标签，’true‘ 有该权限

        try:
            topics_obj = Topics.objects.get(id=int(ids))
        except Exception as e:
            print(e)
            returnDict = {'code': 500, 'message': '获取详情失败'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            audit_dic = {}
            for audit_obj in topics_obj.topicsauditrecord_set.all():
                node_display = ""
                if audit_obj.node == "B":
                    node_display = "分管领导"
                if audit_obj.node == "OPR":
                    node_display = "医院办公室初审"
                if topics_obj.type == 'xz':
                    if audit_obj.node == "YZ/SJ":
                        node_display = "院长意见"
                    if audit_obj.node == "YB/DB":
                        node_display = "医院办公室"
                else:
                    if audit_obj.node == "YB/DB":
                        if topics_obj.topicsauditrecord_set.filter(node="yb_result").count() or topics_obj.type == 'yb':
                            node_display = "医院办公室核稿"
                        else:
                            node_display = "党委办公室"
                    if audit_obj.node == "Y_D_leader":
                        node_display = "党委办公室分管领导"
                    if audit_obj.node == "YZ/SJ":
                        if topics_obj.type == 'db':
                            if topics_obj.is_yb:
                                node_display = "院长意见"
                            else:
                                node_display = "书记意见"
                        else:
                            node_display = "院长意见"
                if audit_obj.node == "yb_result":
                    node_display = "院长办公会会议结果"
                if audit_obj.node == "marks":
                    node_display = "议题备注"
                if audit_obj.node == "transfer":
                    node_display = "提交党委会"
                if audit_obj.node == "db_leader":
                    node_display = "分管领导"
                if audit_obj.node == "PG":
                    node_display = "党委办公室"
                if audit_obj.node == "db_one_step":
                    node_display = "分管领导"
                if audit_obj.node == "db_two_step":
                    node_display = "党委办公室"
                if audit_obj.node == "db_three_step":
                    node_display = "党委办公室分管领导"
                if audit_obj.node == "sj":
                    node_display = "书记意见"
                if audit_obj.node == "db_result":
                    node_display = "党委会会议结果"
                if audit_obj.node == "xz_result":
                    node_display = "行政例会会议结果"
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                      'node': audit_obj.node, 'node_display': node_display, 'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                  'node': audit_obj.node, 'node_display': node_display, 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"), "pdf_path": atta_obj.pdf_path, "file_type": "0",
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3], "id": atta_obj.id} for atta_obj in
                Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]

            received_dict = {}
            if topics_obj.received_foreign:
                received_audit_dic, company_type = {}, ''
                received_obj = topics_obj.received_foreign
                company_type = "yb" if topics_obj.received_foreign.apply_user.company.id == 80 else "db"
                for audit_obj in received_obj.officialdocumentsauditrecord_set.all():
                    if audit_obj.node in received_audit_dic:
                        received_audit_dic[audit_obj.node].append(
                            {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                             'node_display': audit_obj.get_node_display() if audit_obj.node not in ["one", "five"] else "医院办公室" if company_type == 'yb' else "党委办公室", 'audit_note': audit_obj.audit_note,
                             'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '', 'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        received_audit_dic[audit_obj.node] = [
                            {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                             'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display() if audit_obj.node not in ["one", "five"] else "医院办公室" if company_type == 'yb' else "党委办公室",
                             'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                             'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

                    received_dict["audit_dic"] = received_audit_dic
                    received_dict["audit_dep"] = company_type
                    received_dict["apply_detail"] = {
                        "company": topics_obj.received_foreign.apply_user.company.name, "apply_user": topics_obj.received_foreign.apply_user.real_name, "recive_number": topics_obj.received_foreign.recive_number,
                        "send_company": topics_obj.received_foreign.send_company, "send_number": topics_obj.received_foreign.send_number, "recive_time": topics_obj.received_foreign.recive_time.strftime("%Y-%m-%d %H:%M"),
                        "title": topics_obj.received_foreign.title, "content": topics_obj.received_foreign.content, "annotated_text": topics_obj.received_foreign.annotated_text, "time_limit": topics_obj.received_foreign.time_limit,
                        "remarks": topics_obj.received_foreign.remarks
                    }

            help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
            help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
            data_dic = {'apply_user': topics_obj.employee.real_name, 'department': topics_obj.employee.department if 'TW' not in topics_obj.number else "团委", 'state': topics_obj.get_state_str(),
                        'main_file_list': main_file_list, 'number': topics_obj.number, 'topics_name': topics_obj.topics_name, "topic_type": topics_obj.get_type_str(), "pay_type": topics_obj.get_pay_type(), "contract_type": topics_obj.get_contract_type(),
                        'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_text).decode()).decode()), "whether_outweigh": "是" if topics_obj.whether_outweigh == "1" else "否", "whether_bid": "是" if topics_obj.whether_bid == "1" else "否",
                        'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_basis).decode()).decode()), "Payee": topics_obj.Payee, "receiving_account": topics_obj.receiving_account, "opening_bank": topics_obj.opening_bank,
                        'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.solution).decode()).decode()) if topics_obj.type != 'xz' else '', "contract_name": topics_obj.contract_name, "contract_number": topics_obj.contract_number,
                        'db_topics_text': base64.b64decode(topics_obj.db_topics_text).decode() if topics_obj.db_topics_text else "", "application_amount": topics_obj.application_amount, "amount_words": topics_obj.amount_words, "funding_source": topics_obj.get_funding_source(),
                        'db_topics_basis': base64.b64decode(topics_obj.db_topics_basis).decode() if topics_obj.db_topics_basis else "",
                        'db_solution': base64.b64decode(topics_obj.db_solution).decode() if topics_obj.db_solution else "", "received_dict": received_dict,
                        'topics_estimate': topics_obj.topics_estimate, 'help_department': help_department, 'help_department1': help_department1,
                        'jfly': topics_obj.jfly if topics_obj.jfly else "", 'ysje': topics_obj.ysje if topics_obj.ysje else "", 'uuid': topics_obj.uuid, 'audit_list': audit_dic,
                        'yb_number': Topics.objects.get(id=int(topics_obj.HouseToParty_id)).number if topics_obj.HouseToParty_id else '',
                        'is_stop': 'true' if topics_obj.state in ['draft', 'confirm', 'audit', 'yd_leader', 'db_leader', "sj", "refuse", "OPR"] and request.user == topics_obj.employee else 'false',
                        'is_audit': 'true' if topics_obj.state in ['draft', 'confirm', 'audit', 'yd_leader', 'db_leader', "sj", "PG", "db_one_step", "db_two_step", "db_three_step", "OPR"] and topics_obj.current_audit_user == request.user.real_name else 'false',
                        'file_path': Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=topics_obj.uuid) else ''}
            if 'OPR' in audit_dic:
                for jj in audit_dic['OPR']:
                    if jj["state_display"] == '同意':
                        jj["state_display"] = '已审核'
            if 'YB/DB' in audit_dic:
                for aa in audit_dic['YB/DB']:
                    if aa["state_display"] == '同意':
                        aa["state_display"] = '已审核'
            if 'yb_result' in audit_dic:
                for bb in audit_dic['yb_result']:
                    if bb["state_display"] == '同意':
                        bb["state_display"] = ''
            if 'db_result' in audit_dic:
                for dd in audit_dic['db_result']:
                    if dd["state_display"] == '同意':
                        dd["state_display"] = ''
            if 'xz_result' in audit_dic:
                for ee in audit_dic['xz_result']:
                    if ee["state_display"] == '同意':
                        ee["state_display"] = ''
            if 'transfer' in audit_dic:
                for cc in audit_dic['transfer']:
                    if cc["state_display"] == '同意':
                        cc["state_display"] = ''
            returnDict = {'code': 200, 'message': '创建成功', 'data': data_dic}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):  # 议题审核
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        RecordAndPush().OperationRecords(request, "议题管理")
        topics_obj = Topics.objects.get(id=int(id))
        if topics_obj.type == "xz":
            if topics_obj.state == 'draft':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='B', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'audit'
                    topics_obj.current_audit_user = Staffing.objects.get(
                        station="院长").post_personnel.all().first().real_name

                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'confirm':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'unmetting'
                    topics_obj.current_audit_user = ''
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'audit':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'confirm'
                    dbzr = Company.objects.get(id=3).head_people
                    topics_obj.current_audit_user = dbzr.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            else:
                returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            if topics_obj.state == 'draft':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='B', state='unaudit').first()
                if state == 'audit':
                    if topics_obj.type == "yb" and topics_obj.topicsauditrecord_set.filter(node='OPR'):
                        topics_state = 'OPR'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='OPR',
                                                                                                state='unaudit').first().audit_people.real_name
                    else:
                        topics_state = 'confirm'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YB/DB',
                                                                                                state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'OPR':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='OPR', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'confirm'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YB/DB',
                                                                                            state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'confirm':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='YB/DB', state='unaudit').first()
                if state == 'audit':
                    one_record = topics_obj.topicsauditrecord_set.filter(node='B').first()
                    two_step = topics_obj.topicsauditrecord_set.filter(node='Y_D_leader')
                    if two_step:
                        two_record = topics_obj.topicsauditrecord_set.filter(node='Y_D_leader', state='unaudit').first()
                        if one_record.audit_people == two_record.audit_people:
                            two_record.update_time = datetime.now()
                            two_record.state = state
                            two_record.audit_note = audit_note
                            two_record.save()
                            topics_state = 'audit'
                            topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ',
                                                                                                    state='unaudit').first().audit_people.real_name
                        else:
                            topics_state = 'yd_leader'
                            topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='Y_D_leader',
                                                                                                    state='unaudit').first().audit_people.real_name
                    else:
                        topics_state = 'audit'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ',
                                                                                                state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'yd_leader':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='Y_D_leader', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'audit'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ',
                                                                                            state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'audit':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'unmetting'
                    topics_obj.current_audit_user = ''
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'db_leader':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='db_leader', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'sj'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='sj',
                                                                                            state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'sj':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='sj', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'unmetting'
                    topics_obj.current_audit_user = ''
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'PG':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='PG', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'sj'
                    TopicsAuditRecord.objects.create(topics_id=topics_obj, audit_people=Staffing.objects.get(
                        station="书记").post_personnel.all().first(), audit_note='', state='unaudit', node='sj')
                    topics_obj.current_audit_user = Staffing.objects.get(
                        station="书记").post_personnel.all().first().real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'db_one_step':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='db_one_step', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'db_two_step'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='db_two_step',
                                                                                            state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'db_two_step':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='db_two_step', state='unaudit').first()
                if state == 'audit':
                    one_appave = topics_obj.topicsauditrecord_set.filter(node='db_one_step').first()
                    three_appave = topics_obj.topicsauditrecord_set.filter(node='db_three_step').first()
                    if one_appave.audit_people == three_appave.audit_people:
                        topics_state = 'sj'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='sj',
                                                                                                state='unaudit').first().audit_people.real_name
                        three_appave.update_time = one_appave.update_time
                        three_appave.state = one_appave.state
                        three_appave.audit_note = one_appave.audit_note
                        three_appave.save()
                    else:
                        topics_state = 'db_three_step'
                        topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='db_three_step',
                                                                                                state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            elif topics_obj.state == 'db_three_step':
                audit_record = topics_obj.topicsauditrecord_set.filter(node='db_three_step', state='unaudit').first()
                if state == 'audit':
                    topics_state = 'sj'
                    topics_obj.current_audit_user = topics_obj.topicsauditrecord_set.filter(node='sj',
                                                                                            state='unaudit').first().audit_people.real_name
                else:
                    topics_state = 'refuse'
                    topics_obj.current_audit_user = topics_obj.employee.real_name

            else:
                returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        topics_obj.state = topics_state
        topics_obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        if request.user not in topics_obj.already_users.all():
            topics_obj.already_users.add(request.user)
        topic_type = "院办议题" if topics_obj.type == "yb" else "党办议题" if topics_obj.type == "db" else "行政例会"
        applicant = topics_obj.employee.real_name
        ApplicationTime = topics_obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = topics_obj.topics_name[:15] + "……" if len(topics_obj.topics_name) > 15 else topics_obj.topics_name
        try:
            RecordAndPush().MessagePush(User.objects.filter(real_name=topics_obj.current_audit_user).first().openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        except:
            pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 发件箱
class SendInboxApi(LoginRequiredMixin, View):  # 发件箱列表
    def get(self, request):
        page = request.GET.get("page", 1)  # 页码
        search = request.GET.get("search", None)  # 是否查询，是否翻页
        delete_list = request.GET.get("delete_list", None)  # 删除邮件列表
        search_data = request.GET.get("search_data", None)  # 按照时间查询
        search_value = request.GET.get("search_value", None)  # 按照值查询

        if delete_list:
            InboxInfo.objects.filter(id__in=json.loads(delete_list)).update(deleted='b')

        if search_data and not search_value:
            startTime = datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
            endTime = startTime + timedelta(days=1)
            inbox_obj = InboxInfo.objects.filter(proposer=request.user, deleted='a', create_time__range=(startTime, endTime), is_draft=False).order_by("-create_time")
            print(inbox_obj.count())

        elif search_value and not search_data:
            inbox_obj = InboxInfo.objects.filter(Q(title__contains=search_value) | Q(plain_text__contains=search_value), proposer=request.user, deleted='a', is_draft=False).order_by("-create_time")

        elif search_value and search_data:
            startTime = datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
            endTime = startTime + timedelta(days=1)
            inbox_obj = InboxInfo.objects.filter(Q(title__contains=search_value) | Q(plain_text__contains=search_value), proposer=request.user, deleted='a',
                                                 create_time__range=(startTime, endTime), is_draft=False).order_by("-create_time")
        else:
            print("oik")
            inbox_obj = InboxInfo.objects.filter(proposer=request.user, deleted='a', is_draft=False).order_by("-create_time")

        inbox_li = []
        for i in inbox_obj:
            item = {}
            item['message_id'] = i.id
            item['sender_name'] = i.proposer.real_name
            item['sender'] = i.proposer.job_number
            item['title'] = i.title
            item['content'] = i.content.replace("%26nbsp;", '')
            item['plain_text'] = i.plain_text
            item['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M")
            item['ids'] = str(uuid.uuid4())
            item['deleted_id'] = i.id
            inbox_li.append(item)

        page_number = inbox_obj.count() // 15 if inbox_obj.count() % 15 == 0 else (inbox_obj.count() // 15) + 1
        cunt_page = int(page)
        last_page = int(page) - 1
        next_page = int(page) + 1

        if search:
            returnDict = {'code': 200, 'message': '获取成功',
                          'data': {"inbox_li": inbox_li[(int(page) - 1) * 15:int(page) * 15],
                                   "page_number": page_number,
                                   "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page}}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        returnDict = {"code": 200,
                      "message": "success",
                      "data": {'inbox_li': inbox_li[(int(page) - 1) * 15:int(page) * 15], "page_number": page_number,
                       "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page}
                      }
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 收件箱
class SentApi(LoginRequiredMixin, View):
    def get(self, request):
        page = request.GET.get("page", 1)  # 页码
        search = request.GET.get("search", None)  # 是否查询，是否翻页
        search_type = request.GET.get("search_type", 'all')  # 查询类型
        delete_list = request.GET.get("delete_list", None)  # 删除邮件列表
        search_data = request.GET.get("search_data", None)  # 按照时间查询
        search_value = request.GET.get("search_value", None)  # 按照值查询
        all_read = request.GET.get("all_read", None)  # 全部已读
        returnDict, messige_flag = {}, False
        message_id = request.GET.get("message_id", '')
        if message_id:
            messige_flag = True
            inbox_obj = InboxInfo.objects.get(id=message_id)
            inbox_li = []
            item = {}

            recipient = [obj.recipient_name for obj in inbox_obj.inboxinfopeople_set.all()]
            file_path_list = [{"file_path": str(i.file_path), "file_name": i.file_name, "pdf_path": i.pdf_path,
                               "download_path": f"/announcements/file_download?file_path={os.getcwd()}/media/{str(i.file_path)}" if (
                                                                                                                                                'static' not in str(
                                                                                                                                            i.file_path)) and (
                                                                                                                                                'media' not in str(
                                                                                                                                            i.file_path)) else f"/announcements/file_download?file_path={os.getcwd()}{str(i.file_path)}"}
                              for i in Topicsattachments.objects.filter(topics_number=inbox_obj.accessory_uuid)]

            item['message_id'] = inbox_obj.id
            item['sender_name'] = inbox_obj.proposer.real_name
            item['sender'] = inbox_obj.proposer.job_number
            item['recipient_name'] = recipient
            item['recipient'] = []
            item['title'] = inbox_obj.title
            item['message_content'] = inbox_obj.content.replace('%26nbsp;', '&nbsp;')
            item['create_time'] = inbox_obj.create_time.strftime("%Y-%m-%d %H:%M:%S")
            item['file_url'] = file_path_list
            # item['file_url'] = []
            inbox_li.append(item)

            # 更新状态为已读
            inbox_people_obj = request.user.inboxinfopeople_set.get(inbox_id=inbox_obj)
            inbox_people_obj.readed = "read"
            inbox_people_obj.save()

            message_data = {
                'mail_title': inbox_li[0]['title'],
                'recipient_name': inbox_li[0]['recipient_name'],
                'recipient': inbox_li[0]['recipient'],
                'message_content': inbox_li[0]['message_content'].replace('%26nbsp;', '&nbsp;'),
                'create_time': inbox_li[0]['create_time'],
                'sender_name': inbox_li[0]['sender_name'],
                'sender': inbox_li[0]['sender'],
                'file_url': inbox_li[0]['file_url'],
            }
            returnDict = {'code': 200, 'message': '获取成功', 'message_data': message_data}

        # 删除邮件
        if delete_list:
            InboxInfoPeople.objects.filter(id__in=json.loads(delete_list)).update(deleted='b')

        # 全部设为已读
        if all_read:
            request.user.inboxinfopeople_set.filter(deleted='a').update(readed='read')

        if search_type == "all":
            if search_data and not search_value:
                startTime = datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
                endTime = startTime + timedelta(days=1)
                inbox_obj = request.user.inboxinfopeople_set.filter(deleted='a',
                                                                    create_time__range=(startTime, endTime),
                                                                    inbox_id__is_draft=False).order_by("-create_time")

            elif search_value and not search_data:
                inbox_obj = request.user.inboxinfopeople_set.filter(
                    Q(inbox_id__title__contains=search_value) | Q(inbox_id__plain_text__contains=search_value),
                    deleted='a', inbox_id__is_draft=False).order_by("-create_time")

            elif search_value and search_data:
                startTime = datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
                endTime = startTime + timedelta(days=1)
                inbox_obj = request.user.inboxinfopeople_set.filter(
                    Q(inbox_id__title__contains=search_value) | Q(inbox_id__plain_text__contains=search_value),
                    deleted='a', create_time__range=(startTime, endTime), inbox_id__is_draft=False).order_by(
                    "-create_time")
            else:
                inbox_obj = request.user.inboxinfopeople_set.filter(deleted='a', inbox_id__is_draft=False).order_by(
                    "-create_time")

        elif search_type == "unread":
            inbox_obj = request.user.inboxinfopeople_set.filter(readed='unread', deleted='a',
                                                                inbox_id__is_draft=False).order_by("-create_time")

        else:
            inbox_obj = request.user.inboxinfopeople_set.filter(readed='read', deleted='a',
                                                                inbox_id__is_draft=False).order_by("-create_time")

        inbox_li = []
        for i in inbox_obj:
            item = {}
            item['message_id'] = i.inbox_id.id
            item['sender_name'] = i.inbox_id.proposer.real_name
            item['sender'] = i.inbox_id.proposer.job_number
            item['title'] = i.inbox_id.title
            item['read'] = False if i.readed == 'unread' else True
            item['content'] = i.inbox_id.content.replace("%26nbsp;", '')
            item['plain_text'] = i.inbox_id.plain_text
            item['create_time'] = i.inbox_id.create_time.strftime("%Y-%m-%d %H:%M")
            item['ids'] = str(uuid.uuid4())
            item['deleted_id'] = i.id
            inbox_li.append(item)

        page_number = inbox_obj.count() // 15 if inbox_obj.count() % 15 == 0 else (inbox_obj.count() // 15) + 1
        cunt_page = int(page)
        last_page = int(page) - 1
        next_page = int(page) + 1

        if search:
            returnDict = {'code': 200, 'message': '获取成功',
                          'data': {"inbox_li": inbox_li[(int(page) - 1) * 15:int(page) * 15],
                                   "page_number": page_number,
                                   "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page}}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        returnDict = {"code": 200, "message": "success", "data": {'inbox_li': inbox_li[(int(page) - 1) * 15:int(page) * 15], "page_number": page_number,
                       "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page, "returnDict": returnDict, "messige_flag": messige_flag}}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 草稿箱
class DraftsApi(LoginRequiredMixin, View):
    def get(self, request):
        page = request.GET.get("page", 1)  # 页码
        search = request.GET.get("search", None)  # 是否查询，是否翻页
        delete_list = request.GET.get("delete_list", None)  # 删除邮件列表
        search_data = request.GET.get("search_data", None)  # 按照时间查询
        search_value = request.GET.get("search_value", None)  # 按照值查询

        if delete_list:
            InboxInfo.objects.filter(id__in=json.loads(delete_list)).update(deleted='b')
        inbox_obj = InboxInfo.objects.filter(proposer=request.user, deleted='a', is_draft=True).order_by("-create_time")
        if search_value:
            inbox_obj = inbox_obj.filter(Q(title__contains=search_value) | Q(plain_text__contains=search_value)).order_by("-create_time")
        if search_data:
            startTime = datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
            endTime = startTime + timedelta(days=1)
            inbox_obj = inbox_obj.filter(create_time__range=(startTime, endTime)).order_by("-create_time")

        inbox_li = []
        for i in inbox_obj:
            item = {}
            item['message_id'] = i.id
            item['sender_name'] = i.proposer.real_name
            item['sender'] = i.proposer.job_number
            item['title'] = i.title
            item['content'] = i.content.replace("%26nbsp;", '')
            item['plain_text'] = i.plain_text
            item['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M")
            item['ids'] = str(uuid.uuid4())
            item['deleted_id'] = i.id
            inbox_li.append(item)

        page_number = inbox_obj.count() // 15 if inbox_obj.count() % 15 == 0 else (inbox_obj.count() // 15) + 1
        cunt_page = int(page)
        last_page = int(page) - 1
        next_page = int(page) + 1

        if search:
            returnDict = {'code': 200, 'message': '获取成功',
                          'data': {"inbox_li": inbox_li[(int(page) - 1) * 15:int(page) * 15], "page_number": page_number,
                                   "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page}}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        returnDict = {"code": 200, "message": "success", "data": {'inbox_li': inbox_li[(int(page) - 1) * 15:int(page) * 15], "page_number": page_number,
                       "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page}}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 通知公告
class NoticeIndexApi(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        page = request.GET.get('page', 1)
        accept_n = [i.notice_id for i in user.noticepeople_set.all().order_by('-create_time') if
                    i.notice_id.state == 'audit'][(int(page) - 1) * 20:int(page) * 20]
        data_list = [
            {'id': temp.id, 'is_open': temp.is_open,
             'department': temp.create_people.department,
             'content': urllib.parse.unquote(base64.b64decode(base64.b64decode(
                 temp.content).decode()).decode()) if temp.type == 'pc' else base64.b64decode(
                 temp.content).decode(),
             # 'status': temp.state,
             'create_user': temp.create_people.real_name,
             'create_time': temp.create_time.strftime("%Y-%m-%d %H:%M"), 'titile': temp.name} for
            temp in accept_n]
        returnDict = {'code': 200, 'message': '获取成功', 'data_list': data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        name = request.POST.get("name", None)
        is_open = request.POST.get("switchs", None)
        accept_people = request.POST.get("recipient", None)
        content = request.POST.get("content", None)
        fg_people = request.POST.get("fg_people", None)
        file_list = request.POST.get('file_list', None)  # 附件
        user = request.user
        if user.group.level != 'C':
            returnDict = {'code': 500, 'message': '只有C级权限才能提交通知公告'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if not (user.company and user.company.leaders):
            returnDict = {'code': 500, 'message': '该员工所属部门未挂分管领导'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if name and content:
            content = base64.b64encode(content.encode("utf-8")).decode()
            audit_people_obj = User.objects.get(id=int(fg_people))
            if audit_people_obj:
                notice_obj = Notice.objects.create(name=name, is_open=is_open, content=content, create_people=user,
                                                   audit_people=audit_people_obj, adjunct=json.dumps(file_list),
                                                   type='app')
            else:
                returnDict = {'code': 500, 'message': '未找到分管领导，请联系管理员检查'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            returnDict = {'code': 500, 'message': '请填写公告名称和内容'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if notice_obj:
            NoticePeople_list = []
            if accept_people:
                accept_people = re.findall('\((.*?)\)', accept_people)
                accept_people_objs = User.objects.filter(job_number__in=accept_people)
            else:
                accept_people_objs = User.objects.all()

            for accept_people_obj in accept_people_objs:
                NoticePeople_obj = NoticePeople(notice_id=notice_obj, audit_people=accept_people_obj)
                NoticePeople_list.append(NoticePeople_obj)

            NoticePeople.objects.bulk_create(NoticePeople_list)
            AuditRecord.objects.create(notice_id=notice_obj, audit_people=audit_people_obj, audit_note='',
                                       state='unaudit')
        else:
            returnDict = {'code': 500, 'message': '创建失败'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NoticeDetailApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get("id", None)
        user = request.user
        try:
            notice_obj = Notice.objects.get(id=int(id))
        except:
            returnData = {'code': 500, 'message': '获取错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        # notice_people_list = []
        if notice_obj.state == 'audit':
            notice_people_obj = notice_obj.noticepeople_set.filter(audit_people=user, state='accept').first()
            if notice_people_obj:
                notice_people_obj.state = 'accepted'
                notice_people_obj.accepted_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                notice_people_obj.save()
        # print(json.loads(notice_obj.adjunct))
        notice_people_list = []
        read_list = []
        unread_list = []
        sql = "SELECT B.real_name, B.signature_picture, A.accepted_time, A.state FROM announcements_noticepeople A LEFT JOIN tb_users_message B ON A.audit_people_id=B.id WHERE A.notice_id_id=%(notice_id)s"
        with connection.cursor() as cursor:
            cursor.execute(sql, {'notice_id': id})
            noticepeople_all = cursor.fetchall()
        for notice_people in noticepeople_all:
            two_dict = {}
            three_dict = {}
            one_dict = {'name': notice_people[0], 'state': '未读' if notice_people[3] == 'accept' else '已读',
                        'accepted_time': notice_people[2],
                        'signature_picture': '/media/' + notice_people[1] if notice_people[3] == 'accepted' else ''}
            if notice_people[3] == 'accepted':
                two_dict = {'name': notice_people[0], 'state': '未读' if notice_people[3] == 'accept' else '已读',
                            'accepted_time': notice_people[2],
                            'signature_picture': '/media/' + notice_people[1] if notice_people[3] == 'accepted' else ''}
            if notice_people[3] == 'accept':
                three_dict = {'name': notice_people[0], 'state': '未读' if notice_people[3] == 'accept' else '已读',
                              'accepted_time': notice_people[2],
                              'signature_picture': '/media/' + notice_people[1] if notice_people[
                                                                                       3] == 'accepted' else ''}
            notice_people_list.append(one_dict)
            if two_dict:
                read_list.append(two_dict)
            if three_dict:
                unread_list.append(three_dict)
        returnData = {'code': 200, 'message': 'success',
                      'return_dic': {'create_people': notice_obj.create_people.real_name,
                                     'create_people_company': notice_obj.create_people.company.name,
                                     'title': notice_obj.name,
                                     'state': '完结' if notice_obj.get_state_display() == '已审核' else notice_obj.get_state_display(),
                                     'is_audit': 'true' if notice_obj.get_state_display() != '已审核' and request.user == notice_obj.audit_people else 'false',
                                     'creat_time': str(notice_obj.create_time).split(".")[0][:-3],
                                     'is_open': notice_obj.is_open,
                                     'content': urllib.parse.unquote(base64.b64decode(base64.b64decode(notice_obj.content).decode()).decode()) if notice_obj.type == 'pc' else base64.b64decode(notice_obj.content).decode(),
                                     'adjunct': [{"file_name": i.file_name, "file_path": "/media/"+str(i.file_path), "file_size": i.file_size, "upload_time": i.create_time.strftime("%Y-%m-%d %H:%M"),
                                                  "upload_people": i.uploader_user.real_name, 'id': i.id} for i in Topicsattachments.objects.filter(topics_number=notice_obj.uuid)]},
                      'notice_people_list': notice_people_list,
                      'audit_people_list': [
                          {'name': audit_record.audit_people.real_name, 'state': audit_record.get_state_display(),
                           'accepted_time': audit_record.update_time.strftime("%Y-%m-%d %H:%M") if audit_record.state != 'unaudit' else '',
                           'signature_picture': '/media/' + str(audit_record.audit_people.signature_picture) if (audit_record.audit_people.signature_picture and audit_record.state != 'unaudit') else '',
                           'audit_note': audit_record.audit_note} for audit_record in notice_obj.auditrecord_set.all()
                      ],
                      'read_list': read_list,
                      'unread_list': unread_list,
                      }
        return HttpResponse(json.dumps(returnData), content_type="application/json")

    def post(self, request):
        id = request.POST.get("id", None)
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        audit_note = request.POST.get("audit_note", "同意")
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        try:
            notice_obj = Notice.objects.get(id=int(id))
            notice_obj.audit_users_already.add(request.user)
            if notice_obj.state == 'one':
                notice_obj.current_audit_users.clear()
                audit_record = notice_obj.auditrecord_set.filter(node='one', state='unaudit').first()
                if state == 'audit':
                    next_audit_record = notice_obj.auditrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                    notice_obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'eight'
                    notice_obj.current_audit_users.add(notice_obj.create_people)

            elif notice_obj.state == 'two':
                notice_obj.current_audit_users.clear()
                audit_record = notice_obj.auditrecord_set.filter(node='two', state='unaudit').first()
                if state == 'audit':
                    obj_state = 'end'
                else:
                    obj_state = 'eight'
                    notice_obj.current_audit_users.add(notice_obj.create_people)

            else:
                returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        except Exception as e:
            print(e)
            returnData = {'code': 500, 'message': '审批错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        notice_obj.state = obj_state
        notice_obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        returnData = {'code': 200, 'message': 'success！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 公文接口
class ConferenceMemoDetailViewApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        try:
            conference_memo_obj = ConferenceMemo.objects.get(id=id)
            # print(request.user.real_name)
            # if request.user in [record.audit_people for record in conference_memo_obj.conferencememopeople_set.all()]:
            p_obj = conference_memo_obj.conferencememopeople_set.filter(audit_people=request.user, state='accept').first()
            if p_obj:
                p_obj.state = 'accepted'
                p_obj.update_time = datetime.now()
                p_obj.save()

            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", '/'),
                 "pdf_path": atta_obj.pdf_path.replace("\\", '/'),
                 "file_size": atta_obj.file_size,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 'word_path': os.getcwd() + "/media/" + str(atta_obj.file_path).replace("\\", '/'),
                 "uploader": atta_obj.uploader_user.real_name, "id": atta_obj.id,
                 "topics_number": atta_obj.topics_number} for
                atta_obj in
                Topicsattachments.objects.filter(topics_number=conference_memo_obj.number, file_type="0")]

            file_list1 = [
                {"file_name": atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", '/'),
                 "file_size": atta_obj.file_size, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "uploader": User.objects.get(username=atta_obj.uploader).real_name, "id": atta_obj.id,
                 "topics_number": atta_obj.topics_number} for
                atta_obj in
                Topicsattachments.objects.filter(topics_number=conference_memo_obj.number, file_type="1")]

        except Exception as e:
            print(e)
            returnDict = {'code': 500, 'message': '获取错误！请联系管理员！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            audit_dic, audit_list = {}, []
            int_to_str = {1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六"}
            if conference_memo_obj.type not in ["a", "c"]:
                ConfeObj = conference_memo_obj.conferencememoauditrecord_set.filter(state='draft').order_by(
                    "update_time")
                if ConfeObj.count():
                    for kk in range(ConfeObj.count() + 1):
                        dict_name = {"ApproveText": f"审批详情{int_to_str[kk + 1]}"}
                        if kk < ConfeObj.count() and kk == 0:
                            print("===========================1", kk)
                            AppaveTime = ConfeObj[kk].update_time
                            SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(~Q(state='unaudit'),
                                                                                                 update_time__lte=AppaveTime).order_by(
                                "update_time")
                        elif kk == ConfeObj.count():
                            print("===========================2", kk)
                            SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(
                                Q(create_time__gt=ConfeObj[kk - 1].update_time) | Q(state='unaudit')).order_by(
                                "update_time")
                        else:
                            print("===========================3", kk)
                            AppaveTime = ConfeObj[kk].update_time
                            SearchObj = conference_memo_obj.conferencememoauditrecord_set.filter(~Q(state='unaudit'),
                                                                                                 update_time__gt=
                                                                                                 ConfeObj[
                                                                                                     kk - 1].update_time,
                                                                                                 update_time__lte=AppaveTime).order_by(
                                "update_time")

                        for audit_obj in SearchObj:
                            if audit_obj.node in dict_name:
                                dict_name[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                                  'state': audit_obj.state,
                                                                  'node': audit_obj.node,
                                                                  'state_display': audit_obj.get_state_display(),
                                                                  'node_display': audit_obj.get_node_display(),
                                                                  'audit_note': audit_obj.audit_note,
                                                                  'audit_time': audit_obj.update_time.strftime(
                                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                                  'signature_picture': '/media/' + str(
                                                                      audit_obj.audit_people.signature_picture) if (
                                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                            else:
                                dict_name[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                              'state': audit_obj.state,
                                                              'node': audit_obj.node,
                                                              'state_display': audit_obj.get_state_display(),
                                                              'node_display': audit_obj.get_node_display(),
                                                              'audit_note': audit_obj.audit_note,
                                                              'audit_time': audit_obj.update_time.strftime(
                                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                              'signature_picture': '/media/' + str(
                                                                  audit_obj.audit_people.signature_picture) if (
                                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                        audit_list.append(dict_name)

                else:
                    for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all().order_by("update_time"):
                        if audit_obj.node in audit_dic:
                            audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                              'state': audit_obj.state,
                                                              'node': audit_obj.node,
                                                              'state_display': audit_obj.get_state_display(),
                                                              'node_display': audit_obj.get_node_display(),
                                                              'audit_note': audit_obj.audit_note,
                                                              'audit_time': audit_obj.update_time.strftime(
                                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                              'signature_picture': '/media/' + str(
                                                                  audit_obj.audit_people.signature_picture) if (
                                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                        else:
                            audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.state,
                                                          'node': audit_obj.node,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                    audit_list.append(audit_dic)
            else:
                for audit_obj in conference_memo_obj.conferencememoauditrecord_set.all().order_by("update_time"):
                    if audit_obj.node in audit_dic:
                        audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                          'state': audit_obj.state,
                                                          'node': audit_obj.node,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                audit_list.append(audit_dic)

            recive_people = [{'user': record.real_name, 'state': record.get_state_display(),
                              'signature_picture': '/media/' + str(
                                  record.signature_picture) if (
                                      record.signature_picture and record.state == 'accepted') else '',
                              'update_time': record.update_time.strftime(
                                  "%Y-%m-%d %H:%M") if record.state == 'accepted' else ''}
                             for record in conference_memo_obj.conferencememopeople_set.all()]

            data_dic = {
                'id': conference_memo_obj.id,
                'gist': conference_memo_obj.gist,
                'state': conference_memo_obj.get_state_display(),
                'apply_user': conference_memo_obj.apply_user.real_name if conference_memo_obj.type not in ['h', 'f'] else conference_memo_obj.drafter,
                'department': conference_memo_obj.apply_user.department if conference_memo_obj.type not in ['h', 'f'] else conference_memo_obj.drafter_company,
                'drafter': conference_memo_obj.drafter,
                'drafter_company': conference_memo_obj.drafter_company,
                'servings': conference_memo_obj.servings,
                'file_list': file_list,
                'file_list1': file_list1,
                'type': conference_memo_obj.type,
                'conference_memo_text': conference_memo_obj.conference_memo_text,
                'main_company': conference_memo_obj.main_company,
                'vice_company': conference_memo_obj.vice_company,
                'document_number': conference_memo_obj.document_number,
                'number': conference_memo_obj.number,
                'audit_list': audit_list,
                'recive_people': recive_people,
                'len_recive_people': len(recive_people),
                'is_audit': 'true' if conference_memo_obj.state in ['nine', 'one', 'two', 'three', 'four', 'five'] and request.user.id in [i.id for i in conference_memo_obj.current_audit_users.all()] else 'false',
                'is_stop': 'true' if conference_memo_obj.state in ['nine', 'one', 'two', 'three', 'four', 'five', 'eight'] and request.user == conference_memo_obj.apply_user else 'false',
            }
            returnDict = {'code': 200, 'message': '获取成功', 'data': data_dic}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过 abstention 弃权
        hq_people = request.POST.get('hq_people', None)  # 会签人员
        RecordAndPush().OperationRecords(request, "公文管理")
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请联系管理员！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        conference_memo_obj = ConferenceMemo.objects.get(id=id)
        conference_memo_obj.audit_users_already.add(request.user)

        topic_type = "公文审批"
        applicant = conference_memo_obj.apply_user.real_name
        ApplicationTime = conference_memo_obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = conference_memo_obj.conference_memo_text[:15] + "……" if len(conference_memo_obj.conference_memo_text) > 15 else conference_memo_obj.conference_memo_text

        if conference_memo_obj.type in ['a', 'g', 'c', 'i']:
            if conference_memo_obj.state == 'nine':
                if not conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit',
                                                                                audit_people=request.user):
                    returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit',
                                                                                            audit_people=request.user).first()
                audit_record_obj.state = state
                audit_record_obj.audit_note = audit_note
                audit_record_obj.update_time = datetime.now()
                conference_memo_obj.current_audit_users.clear()
                audit_record_obj.save()
                conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit').delete()
                if state == 'audit':
                    if conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG', state='unaudit'):
                        t_state = 'eleven'
                        audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG',
                                                                                                         state='unaudit')
                        for aaa in audit_record_obj_next:
                            conference_memo_obj.current_audit_users.add(aaa.audit_people)
                    else:
                        t_state = 'one'
                        audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB',
                                                                                                         state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                    try:
                        RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type, applicant,
                                                    ApplicationTime, SubjectMatter)
                    except:
                        pass
                else:
                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                    ApplicationTime, SubjectMatter)
                    except:
                        pass
                conference_memo_obj.state = t_state
                conference_memo_obj.save()

                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'eleven':
                if not conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG', state='unaudit',
                                                                                audit_people=request.user):
                    returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG', state='unaudit',
                                                                                            audit_people=request.user).first()
                audit_record_obj.state = state
                audit_record_obj.audit_note = audit_note
                audit_record_obj.update_time = datetime.now()
                conference_memo_obj.current_audit_users.clear()
                audit_record_obj.save()
                if state == 'audit':
                    t_state = 'one'
                    audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB',
                                                                                                     state='unaudit').first()
                    conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                    try:
                        RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type, applicant,
                                                    ApplicationTime, SubjectMatter)
                    except:
                        pass
                else:
                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                    ApplicationTime, SubjectMatter)
                    except:
                        pass
                conference_memo_obj.state = t_state
                conference_memo_obj.save()
                conference_memo_obj.conferencememoauditrecord_set.filter(node='PRG', state='unaudit').delete()
                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'one':
                if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit',
                                                                                audit_people=request.user):
                    returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                conference_memo_obj.current_audit_users.clear()
                audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB',
                                                                                            state='unaudit').first()
                audit_record_obj.state = state
                audit_record_obj.audit_note = audit_note
                audit_record_obj.update_time = datetime.now()
                audit_record_obj.save()
                if state == 'audit':
                    if conference_memo_obj.type in ('b', 'd'):
                        if conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL', state='unaudit'):
                            t_state = 'two'
                            audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(
                                node='YBL/DBL', state='unaudit').first()
                            conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                            try:
                                RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type,
                                                            applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                        else:
                            t_state = 'three'
                            conference_memo_obj.current_audit_users.add(
                                User.objects.get(job_number=conference_memo_obj.apply_user.job_number))
                            try:
                                RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type,
                                                            applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                    else:
                        if conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL', state='unaudit'):
                            t_state = 'two'
                            audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(
                                node='YBL/DBL', state='unaudit').first()
                        else:
                            t_state = 'five'
                            audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(
                                node='YZ/SJ', state='unaudit').first()

                        conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                        try:
                            RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type,
                                                        applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                else:
                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                    ApplicationTime, SubjectMatter)
                    except:
                        pass
                conference_memo_obj.state = t_state
                conference_memo_obj.save()
                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'two':
                if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL', state='unaudit',
                                                                                audit_people=request.user):
                    returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                conference_memo_obj.current_audit_users.clear()
                audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YBL/DBL',
                                                                                            state='unaudit').first()
                audit_record_obj.state = state
                audit_record_obj.audit_note = audit_note
                audit_record_obj.update_time = datetime.now()
                audit_record_obj.save()
                if state == 'audit':
                    if conference_memo_obj.type in ('a', 'c'):
                        t_state = 'three'
                        conference_memo_obj.current_audit_users.add(
                            User.objects.get(job_number=conference_memo_obj.apply_user.job_number))
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                    elif conference_memo_obj.type in ('b', 'd'):
                        t_state = 'three'
                        conference_memo_obj.current_audit_users.add(
                            User.objects.get(job_number=conference_memo_obj.apply_user.job_number))
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'five'
                        audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                         state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                        try:
                            RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type,
                                                        applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                else:
                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                    ApplicationTime, SubjectMatter)
                    except:
                        pass
                conference_memo_obj.state = t_state
                conference_memo_obj.save()
                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'three':
                if conference_memo_obj.type in ('a', 'b', 'c', 'd') and not hq_people:
                    returnData = {'code': 500, 'message': '需要指定会签人员！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                conference_memo_obj.current_audit_users.clear()
                if hq_people:
                    hq_people = re.findall('\((.*?)\)', hq_people)
                    hq_people_objs = User.objects.filter(job_number__in=hq_people)

                    for hq_people_obj in hq_people_objs:
                        ConferenceMemoAuditRecord.objects.create(conference_memo_id=conference_memo_obj,
                                                                 audit_people=hq_people_obj, audit_note='', node='B')
                        conference_memo_obj.current_audit_users.add(hq_people_obj)
                        try:
                            RecordAndPush().MessagePush(hq_people_obj.openid, topic_type, applicant, ApplicationTime,
                                                        SubjectMatter)
                        except:
                            pass

                    conference_memo_obj.state = 'four'
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '指定会签人员成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                else:
                    if state == 'audit':
                        t_state = 'five'
                        if conference_memo_obj.type == 'e':
                            conference_memo_obj.current_audit_users.add(User.objects.get(job_number=9770))
                            try:
                                RecordAndPush().MessagePush(User.objects.get(job_number=9770).openid, topic_type,
                                                            applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                        if conference_memo_obj.type in ('f', 'h'):
                            conference_memo_obj.current_audit_users.add(User.objects.get(job_number=9770))
                            try:
                                RecordAndPush().MessagePush(User.objects.get(job_number=9770).openid, topic_type,
                                                            applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                        if conference_memo_obj.type == 'g':
                            conference_memo_obj.current_audit_users.add(User.objects.get(job_number=9084))
                            try:
                                RecordAndPush().MessagePush(User.objects.get(job_number=9084).openid, topic_type,
                                                            applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'four':
                if conference_memo_obj.type not in ["a", "c"]:
                    if state in ['audit', 'abstention']:
                        t_state = 'five'
                        if conference_memo_obj.current_audit_users.count() == 1:
                            conference_memo_obj.current_audit_users.clear()
                            audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B',
                                                                                                        state='unaudit').first()
                            audit_record_obj.state = state
                            audit_record_obj.audit_note = audit_note
                            audit_record_obj.update_time = datetime.now()
                            audit_record_obj.save()
                            conference_memo_obj.state = t_state
                            conference_memo_obj.save()
                            next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                          state='unaudit').first()
                            conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)
                            try:
                                RecordAndPush().MessagePush(next_qf_people_obj.audit_people.openid, topic_type,
                                                            applicant, ApplicationTime, SubjectMatter)
                            except:
                                pass
                        else:
                            audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B',
                                                                                                        state='unaudit',
                                                                                                        audit_people=request.user).first()
                            audit_record_obj.state = state
                            audit_record_obj.audit_note = audit_note
                            audit_record_obj.update_time = datetime.now()
                            audit_record_obj.save()
                            conference_memo_obj.current_audit_users.remove(request.user)
                            try:
                                RecordAndPush().MessagePush(request.user.openid, topic_type, applicant, ApplicationTime,
                                                            SubjectMatter)
                            except:
                                pass
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.current_audit_users.openid, topic_type,
                                                        applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                        returnData = {'code': 200, 'message': '操作成功！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    else:
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B',
                                                                                                    state='unaudit',
                                                                                                    audit_people=request.user).first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.now()
                        audit_record_obj.save()

                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        conference_memo_obj.state = t_state
                        conference_memo_obj.save()
                        if conference_memo_obj.public_search:
                            public_search_obj = conference_memo_obj.public_search
                            public_search_obj.audit_users_already.add(request.user)
                            public_search_obj.current_audit_users.clear()
                            for audit_user in conference_memo_obj.current_audit_users.all():
                                public_search_obj.current_audit_users.add(audit_user)
                                try:
                                    RecordAndPush().MessagePush(audit_user.openid, topic_type, applicant,
                                                                ApplicationTime, SubjectMatter)
                                except:
                                    pass
                            public_search_obj.state = conference_memo_obj.state
                            public_search_obj.save()
                        returnData = {'code': 200, 'message': '操作成功！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")

                else:
                    if conference_memo_obj.current_audit_users.count() == 1:
                        conference_memo_obj.current_audit_users.clear()
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B',
                                                                                                    state='unaudit').first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.now()
                        audit_record_obj.save()
                        conference_memo_obj.state = "five"
                        conference_memo_obj.save()
                        next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                      state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)

                    else:
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B',
                                                                                                    state='unaudit',
                                                                                                    audit_people=request.user).first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.now()
                        audit_record_obj.save()
                        conference_memo_obj.current_audit_users.remove(request.user)

                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'five':
                if state == 'audit':
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                state='unaudit').first()
                    if conference_memo_obj.type in ['f', 'h', 'g']:
                        t_state = 'ten'
                        next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS',
                                                                                                      state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)
                        try:
                            RecordAndPush().MessagePush(next_qf_people_obj.audit_people.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'eight'
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                else:
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                state='unaudit',
                                                                                                audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()

                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                    ApplicationTime, SubjectMatter)
                    except:
                        pass
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

            if conference_memo_obj.state == 'ten':
                if state == 'audit':
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS',
                                                                                                state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()
                    t_state = 'eight'
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                    ApplicationTime, SubjectMatter)
                    except:
                        pass
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                else:
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS',
                                                                                                state='unaudit',
                                                                                                audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()

                    t_state = 'six'
                    conference_memo_obj.current_audit_users.clear()
                    conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                    try:
                        RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                    ApplicationTime, SubjectMatter)
                    except:
                        pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

        else:
            if conference_memo_obj.type in ['b', 'd']:
                if conference_memo_obj.state == 'one':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit',
                                                                                    audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB',
                                                                                                state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = 'four'
                        countersignature_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B',
                                                                                                        state='unaudit')
                        for aaa in countersignature_obj:
                            conference_memo_obj.current_audit_users.add(aaa.audit_people)
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                elif conference_memo_obj.state == 'four':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='B', state='unaudit',
                                                                                    audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.remove(request.user)
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='B',
                                                                                                state='unaudit',
                                                                                                audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        print("======================", conference_memo_obj.current_audit_users.all().count())
                        if not conference_memo_obj.current_audit_users.all().count():
                            t_state = 'five'
                            yuanzhang_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                     state='unaudit').first()
                            conference_memo_obj.current_audit_users.add(yuanzhang_obj.audit_people)
                        else:
                            t_state = 'four'
                    elif state == 'abstention':
                        if not conference_memo_obj.current_audit_users.all().count():
                            t_state = 'five'
                            yuanzhang_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit').first()
                            conference_memo_obj.current_audit_users.add(yuanzhang_obj.audit_people)
                        else:
                            t_state = 'four'
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                elif conference_memo_obj.state == 'five':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit',
                                                                                    audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                state='unaudit',
                                                                                                audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        if conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit'):
                            t_state = 'ten'
                            BGS_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS',
                                                                                               state='unaudit')
                            conference_memo_obj.current_audit_users.add(BGS_obj.audit_people)
                        else:
                            t_state = 'seven'
                            items = list()
                            if conference_memo_obj.type == 'e':
                                for user in User.objects.all():
                                    obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=user,
                                                               real_name=user.real_name,
                                                               signature_picture=str(user.signature_picture),
                                                               state='accept')
                                    items.append(obj)
                                ConferenceMemoPeople.objects.bulk_create(items)
                                returnData = {'code': 200, 'message': '操作成功！'}
                                return HttpResponse(json.dumps(returnData), content_type="application/json")
                            else:
                                years = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][0]
                                topic_number = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][1]
                                print("years: ", years)
                                print("topic_number: ", topic_number)
                                meet_objs = topic_meeting.objects.filter(topic_type='yb', topic_year=years,
                                                                         meet_number=topic_number)
                                mobiles = []
                                has_been_sent = []
                                for receive_people_obj in meet_objs:
                                    if receive_people_obj.topic.employee not in has_been_sent:
                                        has_been_sent.append(receive_people_obj.topic.employee)
                                        obj = ConferenceMemoPeople(notice_id=conference_memo_obj,
                                                                   audit_people=receive_people_obj.topic.employee,
                                                                   real_name=receive_people_obj.topic.employee.real_name,
                                                                   signature_picture=str(
                                                                       receive_people_obj.topic.employee.signature_picture),
                                                                   state='accept')
                                        items.append(obj)
                                        mobiles.append(receive_people_obj.topic.employee.mobile)

                                leaders_obj = User.objects.filter(group_id__in=[1, 2])
                                for bbb in leaders_obj:
                                    obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=bbb,
                                                               real_name=bbb.real_name,
                                                               signature_picture=str(bbb.signature_picture),
                                                               state='accept')
                                    items.append(obj)
                                    mobiles.append(bbb.mobile)

                                company_obj = Company.objects.filter(id__in=[18, 22, 23])
                                for ccc in company_obj:
                                    obj = ConferenceMemoPeople(notice_id=conference_memo_obj,
                                                               audit_people=ccc.head_people,
                                                               real_name=ccc.head_people.real_name,
                                                               signature_picture=str(ccc.head_people.signature_picture),
                                                               state='accept')
                                    items.append(obj)
                                    mobiles.append(ccc.head_people.mobile)
                                ConferenceMemoPeople.objects.bulk_create(items)
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass

                else:
                    if state == 'audit':
                        conference_memo_obj.current_audit_users.clear()
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS',
                                                                                                    state='unaudit').first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.now()
                        audit_record_obj.save()
                        t_state = 'seven'
                        conference_memo_obj.state = t_state
                        conference_memo_obj.save()

                        items = list()
                        if conference_memo_obj.type == 'e':
                            for user in User.objects.filter(~Q(id__in=[2, 3]), is_delete=0):
                                obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=user,
                                                           real_name=user.real_name,
                                                           signature_picture=str(user.signature_picture),
                                                           state='accept')
                                items.append(obj)
                            ConferenceMemoPeople.objects.bulk_create(items)
                            returnData = {'code': 200, 'message': '操作成功！'}
                            return HttpResponse(json.dumps(returnData), content_type="application/json")
                        else:
                            years = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][0]
                            topic_number = re.findall("〔(.*?)〕(.*?)号", conference_memo_obj.document_number)[0][1]
                            meet_objs = topic_meeting.objects.filter(topic_type='yb', topic_year=years,
                                                                     meet_number=topic_number)
                            mobiles = []
                            for receive_people_obj in meet_objs:
                                obj = ConferenceMemoPeople(notice_id=conference_memo_obj,
                                                           audit_people=receive_people_obj.employee,
                                                           real_name=receive_people_obj.employee.real_name,
                                                           signature_picture=str(
                                                               receive_people_obj.employee.signature_picture),
                                                           state='accept')
                                items.append(obj)
                                mobiles.append(receive_people_obj.mobile)

                            leaders_obj = User.objects.filter(group_id__in=[1, 2])
                            for bbb in leaders_obj:
                                obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=bbb,
                                                           real_name=bbb.real_name,
                                                           signature_picture=str(bbb.signature_picture), state='accept')
                                items.append(obj)
                                mobiles.append(bbb.mobile)

                            company_obj = Company.objects.filter(id__in=[18, 22, 23])
                            for ccc in company_obj:
                                obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=ccc,
                                                           real_name=ccc.real_name,
                                                           signature_picture=str(ccc.signature_picture), state='accept')
                                items.append(obj)
                                mobiles.append(ccc.mobile)
                            ConferenceMemoPeople.objects.bulk_create(items)

                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                        returnData = {'code': 200, 'message': '操作成功！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    else:
                        audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS',
                                                                                                    state='unaudit',
                                                                                                    audit_people=request.user).first()
                        audit_record_obj.state = state
                        audit_record_obj.audit_note = audit_note
                        audit_record_obj.update_time = datetime.now()
                        audit_record_obj.save()

                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                        conference_memo_obj.state = t_state
                        conference_memo_obj.save()
                        returnData = {'code': 200, 'message': '操作成功！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")

                conference_memo_obj.state = t_state
                conference_memo_obj.save()
                returnData = {'code': 200, 'message': '操作成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                if conference_memo_obj.state == 'nine':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit',
                                                                                    audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D',
                                                                                                state='unaudit',
                                                                                                audit_people=request.user).first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj.save()
                    conference_memo_obj.conferencememoauditrecord_set.filter(node='C/D', state='unaudit').delete()
                    if state == 'audit':
                        t_state = 'one'
                        audit_record_obj_next = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB',
                                                                                                         state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(audit_record_obj_next.audit_people)
                        try:
                            RecordAndPush().MessagePush(audit_record_obj_next.audit_people.openid, topic_type,
                                                        applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                if conference_memo_obj.state == 'one':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB', state='unaudit',
                                                                                    audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YB/DB',
                                                                                                state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = "five"
                        next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                      state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)
                        try:
                            RecordAndPush().MessagePush(next_qf_people_obj.audit_people.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant,
                                                        ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                if conference_memo_obj.state == 'five':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ', state='unaudit',
                                                                                    audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='YZ/SJ',
                                                                                                state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = "ten"
                        next_qf_people_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit').first()
                        conference_memo_obj.current_audit_users.add(next_qf_people_obj.audit_people)
                        try:
                            RecordAndPush().MessagePush(next_qf_people_obj.audit_people.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

                if conference_memo_obj.state == 'ten':
                    if not conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit', audit_people=request.user):
                        returnData = {'code': 500, 'message': '该节点已经审核完毕！请查看是否已审核！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")
                    conference_memo_obj.current_audit_users.clear()
                    audit_record_obj = conference_memo_obj.conferencememoauditrecord_set.filter(node='BGS', state='unaudit').first()
                    audit_record_obj.state = state
                    audit_record_obj.audit_note = audit_note
                    audit_record_obj.update_time = datetime.now()
                    audit_record_obj.save()
                    if state == 'audit':
                        t_state = "eight"
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    else:
                        t_state = 'six'
                        conference_memo_obj.current_audit_users.clear()
                        conference_memo_obj.current_audit_users.add(conference_memo_obj.apply_user)
                        try:
                            RecordAndPush().MessagePush(conference_memo_obj.apply_user.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                        except:
                            pass
                    conference_memo_obj.state = t_state
                    conference_memo_obj.save()
                    returnData = {'code': 200, 'message': '操作成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")


class ConferenceMemoReceive(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        receive_people = request.POST.get('receive_people', None)
        conference_memo_obj = ConferenceMemo.objects.get(id=id)
        conference_memo_obj.state = 'seven'
        conference_memo_obj.save()
        conference_memo_obj.current_audit_users.clear()
        items = list()
        if conference_memo_obj.type == 'e':
            for user in User.objects.all():
                obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=user,
                                           real_name=user.real_name,
                                           signature_picture=str(user.signature_picture), state='accept')
                items.append(obj)
            ConferenceMemoPeople.objects.bulk_create(items)
            returnData = {'code': 200, 'message': '操作成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            if not receive_people:
                returnData = {'code': 200, 'message': '需收阅指定人员！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            receive_people = re.findall('\((.*?)\)', receive_people)
            receive_people_objs = User.objects.filter(job_number__in=receive_people)
            mobiles = []
            for receive_people_obj in receive_people_objs:
                obj = ConferenceMemoPeople(notice_id=conference_memo_obj, audit_people=receive_people_obj,
                                           real_name=receive_people_obj.real_name,
                                           signature_picture=str(receive_people_obj.signature_picture),
                                           state='accept')
                items.append(obj)
                mobiles.append(receive_people_obj.mobile)
            ConferenceMemoPeople.objects.bulk_create(items)
            returnData = {'code': 200, 'message': '操作成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


# 上级来文接口
class OfficialDocumentsDetailViewApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        office_obj = OfficialDocuments.objects.get(id=int(id))
        audit_dic, flow_dict = {}, {}
        for audit_obj in office_obj.officialdocumentsauditrecord_set.all():
            if audit_obj.get_node_display() == "one":
                node_display = "科室负责人"
            elif audit_obj.get_node_display() == "two":
                node_display = "分管领导"
            elif audit_obj.get_node_display() == "three":
                node_display = "接收科室回执"
            elif audit_obj.get_node_display() == "four":
                node_display = "分管领导"
            elif audit_obj.get_node_display() == "five":
                node_display = "科室负责人"
            else:
                node_display = audit_obj.get_node_display()
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': node_display, 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in office_obj.officialdocumentsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': node_display, 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"), "file_type": atta_obj.file_type,
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=office_obj.uuid)]

        ReceivingObj = office_obj.officialdocumentspeople_set.all()
        ReceivingList = []
        for receiving in ReceivingObj:
            ReceivingList.append({"receiving": receiving.audit_people.real_name, "time": receiving.update_time.strftime("%Y-%m-%d %H:%M"), "state": receiving.state,
                                  "signature_picture": '/media/' + str(receiving.audit_people.signature_picture) if receiving.audit_people.signature_picture else ''})

        withdrawal = "false"
        received_obj = office_obj.officialdocumentsauditrecord_set.filter(audit_people=request.user, state="audit")
        if received_obj.count():
            if received_obj.last().node == "one" and office_obj.state == "two":
                withdrawal = "true"
            elif received_obj.last().node == "two" and office_obj.state == "three":
                withdrawal = "true"
            elif received_obj.last().node == "three" and (office_obj.state == "three" or office_obj.state == "four"):
                withdrawal = "true"
            elif received_obj.last().node == "four" and office_obj.state == "five":
                withdrawal = "true"
            else:
                withdrawal = "false"
        context = {"id": office_obj.id, "state": office_obj.state, "apply_user": office_obj.apply_user.real_name, "department": office_obj.apply_user.company.name, 'audit_dic': audit_dic, "file_list": file_list, "withdrawal": withdrawal,
                   "send_number": office_obj.send_number, "recive_number": office_obj.recive_number, "send_company": office_obj.send_company, "title": office_obj.title, "uuid": office_obj.uuid,
                   "content": office_obj.content, "annotated_text": office_obj.annotated_text, "time_limit": office_obj.time_limit, "remarks": office_obj.remarks,
                   'is_edit': 'true' if (office_obj.state == 'eight' and office_obj.apply_user == request.user) else 'false',
                   'is_audit': 'true' if office_obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in office_obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if office_obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == office_obj.apply_user else 'false',
                   'flow_dict': flow_dict, "recive_time": office_obj.recive_time.strftime("%Y-%m-%d %H:%M"),
                   "leader_obj": [{"id": i.id, "real_name": i.real_name} for i in User.objects.filter(group_id__in=[1, 2])], "recive_people": ReceivingList,
                   'file_path': Topicsattachments.objects.filter(topics_number=office_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=office_obj.uuid) else ""
                   }
        returnDict = {'code': 200, 'message': '获取成功', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        flow_id = request.POST.get("id", '')
        opinion_detail = request.POST.get("audit_note", '')
        approve = request.POST.get("state", '')

        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "上级来文")
        except:
            pass

        obj = OfficialDocuments.objects.get(id=int(flow_id))

        if not obj.officialdocumentsauditrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 500, 'message': '当前节点已审批，请勿重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        if obj.version != '3':
            obj.audit_users_already.add(request.user)
            if obj.state == "one":
                obj.current_audit_users.clear()
                audit_record = obj.officialdocumentsauditrecord_set.filter(node='one', state='unaudit').first()
                if approve == "audit":
                    leader_prople = request.POST.get("leader_prople", '')
                    AuditPeople = User.objects.get(id=int(leader_prople))
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="two")
                    obj.current_audit_users.add(AuditPeople)
                    obj.leaders = AuditPeople
                    obj.state = "two"
                else:
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "two":
                obj.current_audit_users.remove(request.user)
                audit_record = obj.officialdocumentsauditrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
                if approve == "audit":
                    Distributors = request.POST.get("Distributors", '')
                    ReadingPersonnel = request.POST.get("ReadingPersonnel", '')
                    distributors_list = re.findall('\((.*?)\)', Distributors)
                    for i in distributors_list:
                        AuditPeople = User.objects.get(job_number=i)
                        if not OfficialDocumentsAuditRecord.objects.filter(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="three").count():
                            OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="three")

                    if not obj.current_audit_users.all().count():
                        two_already_step = []
                        all_two_step = obj.officialdocumentsauditrecord_set.filter(node='two')
                        for two_step in all_two_step:
                            if two_step.audit_people not in two_already_step:
                                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=two_step.audit_people, node="four")
                        five_step = Company.objects.get(id=80).head_people if obj.apply_user.company.id == 80 else Company.objects.get(id=3).head_people
                        OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=five_step, node="five")
                        obj.state = "three"
                        all_three_step = obj.officialdocumentsauditrecord_set.filter(node='three')
                        for three_step in all_three_step:
                            obj.current_audit_users.add(three_step.audit_people)

                    items = []
                    receive_people = re.findall('\((.*?)\)', ReadingPersonnel)
                    receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
                    for receive_people_obj in receive_people_objs:
                        off_obj = OfficialDocumentsPeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
                        items.append(off_obj)
                    OfficialDocumentsPeople.objects.bulk_create(items)

                elif approve == "end":
                    obj.state = "six"
                    obj.type = "e"

                else:
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "three":
                audit_record = obj.officialdocumentsauditrecord_set.get(node='three', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    obj.current_audit_users.remove(request.user)
                    audit_record.state = approve
                    audit_record.save()
                    Receipt = request.POST.get("Receipt", '')
                    audit_record.img_path = Receipt
                    if obj.officialdocumentsauditrecord_set.filter(node='three', state='unaudit').count():
                        obj.state = "three"
                    else:
                        obj.state = "four"
                        obj.type = "a"
                        all_four_step = obj.officialdocumentsauditrecord_set.filter(node='four')
                        for four_step in all_four_step:
                            obj.current_audit_users.add(four_step.audit_people)
                else:
                    obj.current_audit_users.clear()
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "four":
                obj.current_audit_users.remove(request.user)
                audit_record = obj.officialdocumentsauditrecord_set.get(node='four', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    if not obj.current_audit_users.all().count():
                        obj.state = "five"
                        five_step = obj.officialdocumentsauditrecord_set.filter(node='five', state='unaudit')
                        obj.current_audit_users.add(five_step.first().audit_people)
                else:
                    obj.state = "three"
                    obj.type = "f"
                    set_list = []
                    three_step = obj.officialdocumentsauditrecord_set.filter(node='three')
                    for step in three_step:
                        if step.audit_people not in set_list:
                            OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=step.audit_people, node="three")
                            obj.current_audit_users.add(step.audit_people)
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=obj.leaders, node="four")

            else:
                obj.current_audit_users.clear()
                audit_record = obj.officialdocumentsauditrecord_set.get(node='five', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    obj.state = "six"
                    obj.type = "e"
                else:
                    obj.state = "eight"
                    obj.current_audit_users.add(obj.apply_user)

            audit_record.update_time = datetime.datetime.now()
            audit_record.state = approve
            audit_record.audit_note = opinion_detail
            audit_record.save()
            obj.save()

        else:
            obj.audit_users_already.add(request.user)
            obj.current_audit_users.remove(request.user)
            if obj.state == "one":
                audit_record = obj.officialdocumentsauditrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
                if approve == "audit":
                    leader_prople = request.POST.get("leader_prople", '')
                    AuditPeople = User.objects.get(id=int(leader_prople))
                    OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="two")
                    obj.current_audit_users.add(AuditPeople)
                    obj.leaders = AuditPeople
                    obj.state = "two"
                else:
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "two":
                audit_record = obj.officialdocumentsauditrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
                if approve == "audit":
                    Distributors = request.POST.get("Distributors", '')             # 分发人员
                    increase_level = request.POST.get("increase_Level", '')         # 是否提升审批等级
                    LeaderList = request.POST.get("LeaderList", '')                      # 阅示领导
                    distributors_list = re.findall('\((.*?)\)', Distributors)
                    obj.increase_Level = increase_level
                    for i in distributors_list:
                        AuditPeople = User.objects.get(job_number=i)
                        if not OfficialDocumentsAuditRecord.objects.filter(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="three").count():
                            OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=AuditPeople, node="three")
                            obj.current_audit_users.add(AuditPeople)

                    if increase_level == '2':
                        two_already_step = []
                        all_two_step = obj.officialdocumentsauditrecord_set.filter(node='two')
                        for two_step in all_two_step:
                            if two_step.audit_people not in two_already_step:
                                OfficialDocumentsAuditRecord.objects.create(official_documents_id=obj, state="unaudit", audit_people=two_step.audit_people, node="four")

                    obj.state = "three"
                    items = []
                    try:
                        leader_list = json.loads(LeaderList)
                    except:
                        leader_list = LeaderList
                    leader_list_objs = User.objects.filter(job_number__in=leader_list, is_delete="0")
                    for leader_list_obj in leader_list_objs:
                        off_obj = OfficialDocumentsPeople(notice_id=obj, state='accept', audit_people=leader_list_obj)
                        items.append(off_obj)
                    OfficialDocumentsPeople.objects.bulk_create(items)
                else:
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            elif obj.state == "three":
                if obj.increase_Level == '1':
                    returnData = {'code': 400, 'message': '审核等级已提升，请发起以提升请！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")
                audit_record = obj.officialdocumentsauditrecord_set.get(node='three', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    audit_record.state = approve
                    audit_record.save()
                    Receipt = request.POST.get("Receipt", '')
                    audit_record.img_path = Receipt
                    obj.state = "four"
                    all_four_step = obj.officialdocumentsauditrecord_set.filter(node='four')
                    for four_step in all_four_step:
                        obj.current_audit_users.add(four_step.audit_people)
                else:
                    obj.current_audit_users.clear()
                    obj.state = "eight"
                    obj.type = "f"
                    obj.current_audit_users.add(obj.apply_user)

            else:
                obj.current_audit_users.clear()
                audit_record = obj.officialdocumentsauditrecord_set.get(node='four', state='unaudit', audit_people=request.user)
                if approve == "audit":
                    obj.state = "six"
                    obj.type = "e"
                else:
                    obj.state = "eight"
                    obj.current_audit_users.add(obj.apply_user)

            audit_record.update_time = datetime.now()
            audit_record.state = approve
            audit_record.audit_note = opinion_detail
            audit_record.save()
            obj.save()

        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "上级来文"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class RevokeApprovalViewApi(LoginRequiredMixin, View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = OfficialDocuments.objects.get(id=int(flow_id))
        if obj.state == "one" or obj.state == "six" or obj.state == "two":
            returnData = {'code': 400, 'message': '该节点无法撤回审批！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif obj.state == "three":
            if obj.officialdocumentsauditrecord_set.filter(~Q(state='unaudit'), audit_people=request.user).last().node == "two":
                record_obj = obj.officialdocumentsauditrecord_set.filter(node='two', audit_people=request.user).last()
                record_obj.state = "unaudit"
                record_obj.audit_note = ""
                record_obj.save()
                obj.current_audit_users.clear()
                obj.current_audit_users.add(record_obj.audit_people)
                obj.state = "two"
                obj.save()
                obj.officialdocumentsauditrecord_set.filter(node='three').delete()
                obj.officialdocumentsauditrecord_set.filter(node='four').delete()
                obj.officialdocumentsauditrecord_set.filter(node='five').delete()
                obj.officialdocumentspeople_set.all().delete()
            else:
                Topicsattachments.objects.filter(file_type="1", uploader_user=request.user).delete()
                record_obj = obj.officialdocumentsauditrecord_set.filter(audit_people=request.user).last()
                record_obj.state = "unaudit"
                record_obj.audit_note = ""
                record_obj.save()
                obj.current_audit_users.add(record_obj.audit_people)
                obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif obj.state == "four":
            Topicsattachments.objects.filter(file_type="1", uploader_user=request.user).delete()
            record_obj = obj.officialdocumentsauditrecord_set.filter(node='three', audit_people=request.user).last()
            record_obj.state = "unaudit"
            record_obj.audit_note = ""
            record_obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(record_obj.audit_people)
            obj.state = "three"
            obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            record_obj = obj.officialdocumentsauditrecord_set.filter(node='four', audit_people=request.user).last()
            record_obj.state = "unaudit"
            record_obj.audit_note = ""
            record_obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(record_obj.audit_people)
            obj.state = "four"
            obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class SuperiorsApprovalViewApi(LoginRequiredMixin, View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = Correspondence.objects.get(id=int(flow_id))
        if obj.state == "one" or obj.state == "six" or obj.state == "two":
            returnData = {'code': 400, 'message': '该节点无法撤回审批！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif obj.state == "three":
            if obj.correspondencerecord_set.filter(~Q(state='unaudit'), audit_people=request.user).last().node == "two":
                record_obj = obj.correspondencerecord_set.filter(node='two', audit_people=request.user).last()
                record_obj.state = "unaudit"
                record_obj.audit_note = ""
                record_obj.save()
                obj.current_audit_users.clear()
                obj.current_audit_users.add(record_obj.audit_people)
                obj.state = "two"
                obj.save()
                obj.correspondencerecord_set.filter(node='three').delete()
                obj.correspondencerecord_set.filter(node='four').delete()
                obj.correspondencerecord_set.filter(node='five').delete()
                obj.correspondencepeople_set.all().delete()
            else:
                Topicsattachments.objects.filter(file_type="1", uploader_user=request.user).delete()
                record_obj = obj.correspondencerecord_set.filter(audit_people=request.user).last()
                record_obj.state = "unaudit"
                record_obj.audit_note = ""
                record_obj.save()
                obj.current_audit_users.add(record_obj.audit_people)
                obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        elif obj.state == "four":
            Topicsattachments.objects.filter(file_type="1", uploader_user=request.user).delete()
            record_obj = obj.correspondencerecord_set.filter(node='three', audit_people=request.user).last()
            record_obj.state = "unaudit"
            record_obj.audit_note = ""
            record_obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(record_obj.audit_people)
            obj.state = "three"
            obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            record_obj = obj.correspondencerecord_set.filter(node='four', audit_people=request.user).last()
            record_obj.state = "unaudit"
            record_obj.audit_note = ""
            record_obj.save()
            obj.current_audit_users.clear()
            obj.current_audit_users.add(record_obj.audit_people)
            obj.state = "four"
            obj.save()
            returnData = {'code': 200, 'message': '撤回成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class OfficialDocumentsReceive(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        receive_people = request.POST.get('receive_people', None)
        message = request.POST.get('message', None)
        obj = OfficialDocuments.objects.get(id=int(id))
        items = []
        receive_people = re.findall('\((.*?)\)', receive_people)
        receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
        mobile_list = []
        for receive_people_obj in receive_people_objs:
            mobile_list.append(receive_people_obj.mobile)
            off_obj = OfficialDocumentsPeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
            items.append(off_obj)
        obj.current_audit_users.clear()
        OfficialDocumentsPeople.objects.bulk_create(items)
        if receive_people:
            obj.type = 'd'
        else:
            obj.type = 'e'
        obj.save()
        if str(message) == '1':
            message_str = f'上级来文：您有一份“{obj.recive_number}”“{obj.title}”的上级来文需要处理接收，请您在OA系统上查收。'
            send_mssage(mobile_list, message_str)
        returnDict = {'code': 200, 'message': '操作成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class UpdateCompany(LoginRequiredMixin, View):
    def get(self, request):
        com_objs = Company.objects.all()
        for com_obj in com_objs:
            if com_obj.deputy_director:
                deputy_director_list = com_obj.deputy_director.split(', ')
                users = User.objects.filter(real_name__in=deputy_director_list)
                for user in users:
                    com_obj.deputy_director_ids.add(user)

        returnDict = {'code': 200, 'message': '操作成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


def str_time(timeStr):
    return time.mktime(time.strptime(timeStr, '%Y-%m-%d %H:%M:%S'))


# 会议接口
class RoomReservationApi(LoginRequiredMixin, View):
    def get(self, request):
        real_name = request.user.real_name
        department = request.user.company.name
        page = request.GET.get("page", 1)
        # search_type = request.GET.get("search", None)
        select_data = ConferenceRoomApplication.objects.filter(~Q(status='2')).order_by("statr_time")
        now_time = datetime.now()
        # add_time = (datetime.now()+timedelta(days=5))
        flag, name_list, particulars, meeting_adress, meeting_prople, meeting_time_day, meeting_time_start, meeting_time_end = True, [], "", "", "", "", "", ""
        calendar = {}
        app_calendar = {}

        meet_list = []
        for select in select_data:
            if select.status == "3":
                continue
            if select.statr_time <= now_time and select.end_time >= now_time:
                status = "1"                                                                    # 进行中
            elif now_time <= select.statr_time:
                status = '0'                                                                    # 未开始
            elif now_time >= select.end_time:
                status = "2"                                                                    # 已结束
            else:
                status = "2"                                                                    # 已结束

            select.status = status
            select.save()
        for k, v in calendar.items():
            app_calendar['date'] = k
            app_calendar['info'] = v
        all_data = ConferenceRoomApplication.objects.filter(Q(conferee__contains=request.user.job_number) | Q(names=real_name, department=department), status__in=['0', '1'], state='audit').order_by("-id")
        all_data_list = []
        for tt in all_data[(int(page) - 1) * 20:int(page) * 20]:
            one_dict = {}
            one_dict["id"] = tt.id
            one_dict["name"] = tt.names
            one_dict["department"] = tt.department
            one_dict["particular"] = tt.particulars
            one_dict["start_time"] = str(tt.statr_time)[:-3]
            one_dict["end_time"] = str(tt.end_time)[:-3]
            one_dict["meeting_root"] = tt.meeting_root
            one_dict["status"] = "未开始" if tt.status == "0" else "进行中" if tt.status == "1" else "结束"
            one_dict["conferee"] = ', '.join(json.loads(tt.conferee)[0])
            all_data_list.append(one_dict)

        returnData = {"code": 200, "status": "success", "name_list": name_list,
                      "calendar": app_calendar, "all_data_list": all_data_list,
                      "data": all_data.count()}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

    def post(self, request):
        # now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        names = request.user.real_name
        department = request.user.company.name
        particulars = request.POST.get('particulars', None)
        time_start = request.POST.get('time_start', None)
        time_end = request.POST.get('time_end', None)
        meeting_root = request.POST.get('meeting_root', None)
        Number_people = request.POST.get('Number_people', None)
        conferee = request.POST.get('conferee', None)
        time_start = datetime.strptime(time_start, '%Y-%m-%d %H:%M:%S')
        time_end = datetime.strptime(time_end, '%Y-%m-%d %H:%M:%S')
        if time_start < datetime.now():
            returnData = {"code": 200, "message": "会议室只能预定当前时间之后！"}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        if time_start.day != time_end.day:
            returnData = {"code": 200, "message": "会议预定时间只能在一天之内！"}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        select_data = ConferenceRoomApplication.objects.filter(~Q(status='2'), meeting_root=meeting_root)

        for select in select_data:
            if time_start >= select.statr_time and time_end <= select.end_time:
                returnData = {"code": 200, "message": "该会议室正在使用中！"}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if time_end >= select.statr_time and time_end <= select.end_time:
                returnData = {"code": 200, "message": "该会议室正在使用中！"}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            if time_start <= select.statr_time and time_end >= select.end_time:
                returnData = {"code": 200, "status": "success", "data": [], "message": "该会议室正在使用中！"}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

        save_data, name_list, job_num = [], [], []
        # print(conferee)
        confereeList = []
        if conferee:
            confereeList = [i for i in conferee.split(",") if i]
        # print(confereeList)

        for tt in confereeList:
            tt_list = tt.split("(")
            name_list.append(tt_list[0])
            job_num.append(tt_list[1][:-1])
        save_data.append(name_list)
        save_data.append(job_num)
        # print(save_data)
        # [["\u6881\u4e1c", "\u53f6\u9716", "\u9648\u8bad\u519b"], ["6688", "6888", "8006"]]
        ConferenceRoomApplication.objects.create(names=names, department=department, particulars=particulars,
                                                 statr_time=time_start, end_time=time_end, meeting_root=meeting_root,
                                                 Number_people=Number_people, conferee=json.dumps(save_data))

        returnData = {"code": 200, "message": "预定成功！"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MeetingPreviewApi(LoginRequiredMixin, View):
    def post(self, request):
        meet_room_obj = ConferenceRoomApplication.objects.filter(status__in=[1, 0], state='audit')
        returnData = {"code": 200, "message": "ok！",
                      "data": [{"particulars": obj.particulars, "meeting_root": obj.meeting_root, "statr_time": obj.statr_time.strftime(
                                                      "%Y-%m-%d %H:%M"), "end_time": obj.end_time.strftime("%Y-%m-%d %H:%M")} for obj in meet_room_obj]}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MeetingApprovalApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get("id")
        obj = ConferenceRoomApplication.objects.get(id=int(id))
        history_list_objs = ConferenceRoomApplication.objects.filter(statr_time__range=(f"{obj.statr_time.strftime('%Y-%m-%d')} 00:00:00", f"{obj.end_time.strftime('%Y-%m-%d')} 23:59:59"), meeting_root=obj.meeting_root, status__in=['0', '1', '2']).order_by('create_time')
        history_list, conflict_list, not_conflict_list = [], [], []
        for i in history_list_objs:
            if i.state != 'unaudit':
                conflict = '1'
            else:
                clash_obj = ConferenceRoomApplication.objects.filter(
                    Q(statr_time__lte=i.statr_time, end_time__gte=i.statr_time) | Q(statr_time__lte=i.end_time, end_time__gte=i.end_time), ~Q(id=obj.id), meeting_root=obj.meeting_root, status__in=['0', '1', '2'])
                if clash_obj.count() >= 2:
                    conflict = '2'
                else:
                    if clash_obj.count() == 0:
                        conflict = '3'
                    else:
                        if i.statr_time >= obj.statr_time and i.end_time <= obj.end_time:
                            conflict = '2'
                        elif i.statr_time <= obj.statr_time and i.end_time >= obj.end_time:
                            conflict = '2'
                        elif i.statr_time <= obj.statr_time and i.end_time <= obj.end_time and i.end_time >= obj.statr_time:
                            conflict = '2'
                        elif i.statr_time >= obj.statr_time and i.end_time >= obj.end_time and i.statr_time <= obj.end_time:
                            conflict = '2'
                        else:
                            conflict = '3'
            one_dict = {"meeting_root": i.meeting_root, "create_time": i.create_time.strftime("%Y-%m-%d %H:%M"), "statr_time": i.statr_time.strftime("%Y-%m-%d %H:%M"),
                        "end_time": i.end_time.strftime("%Y-%m-%d %H:%M"),
                        "status": i.status, "state": i.state, "id": i.id, "conflict": conflict, "names": i.names,
                        "particulars": i.particulars, "SameTop": '1' if i.id == int(id) else '2'}
            if conflict == '2':
                conflict_list.append(one_dict)
            else:
                not_conflict_list.append(one_dict)

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.uuid)]

        history_list = conflict_list + not_conflict_list
        DzbZhuRen = Company.objects.get(id=3).head_people
        context = {'obj': {"names": obj.names, "department": obj.department, "statr_time": obj.statr_time.strftime("%Y-%m-%d %H:%M"), "end_time": obj.end_time.strftime("%Y-%m-%d %H:%M"), "meeting_root": obj.meeting_root, "particulars": obj.particulars, "conferee": ','.join([i for i in json.loads(obj.conferee)[0] if i.strip()]), "Number_people": obj.Number_people,
                           "file_list": file_list, "is_audit": 'true' if obj.state == 'unaudit' and request.user == DzbZhuRen else 'false', 'state': obj.get_state_display()}, 'realname': request.user.real_name, 'position': request.user.post, 'history_list_objs': history_list, 'signature_picture': str(DzbZhuRen.signature_picture)}
        return HttpResponse(json.dumps(context), content_type="application/json")

    def post(self, request):
        id = request.POST.get("id", None)
        obj = ConferenceRoomApplication.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        if not state:
            returnData = {'code': 500, 'message': '参数错误，请传state参数！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        if state == 'audit':
            history_objs = ConferenceRoomApplication.objects.filter(
                Q(statr_time__range=[obj.statr_time + timedelta(seconds=1), obj.end_time + timedelta(seconds=-1)]) | Q(
                    end_time__range=[obj.statr_time + timedelta(seconds=1),
                                     obj.end_time + timedelta(seconds=-1)])).filter(state='audit',
                                                                                    meeting_root=obj.meeting_root)

            if history_objs.count() > 0:
                returnDict = {'code': 500, 'message': '该会议室在本时间段内已被占用！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = state
        obj.audit_note = audit_note
        obj.audit_people = None
        obj.save()
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class RoomDetailApi(LoginRequiredMixin, View):
    def post(self, request):
        """
        __gte 大于等于
        __lte 小于等于
        """
        search_time = request.POST.get("search_time", '')  # 查询时间
        data_list = []
        today_data_start = ConferenceRoomApplication.objects.filter(
            hour_statr_time__gte=time.strftime(f"{search_time} 00:00"),
            hour_end_time__lte=time.strftime(f"{search_time} 23:00"),
            status__in=[1, 2, 0], state='audit').order_by("hour_statr_time")

        today_data_end = ConferenceRoomApplication.objects.filter(
            hour_statr_time__gte=time.strftime(f"{search_time} 00:00"),
            hour_end_time__lte=time.strftime(f"{search_time} 23:00"),
            status__in=[1, 2, 0], state='audit').order_by("-hour_end_time")

        print(today_data_start.count())
        start_hour, end_hour = 5, 22
        if today_data_start:
            if int(str(today_data_start[0].hour_statr_time).split(" ")[1].split(":")[0]) < start_hour:
                start_hour = int(str(today_data_start[0].hour_statr_time).split(" ")[1].split(":")[0])
        if today_data_end:
            if int(str(today_data_end[0].hour_end_time).split(" ")[1].split(":")[0]) > end_hour:
                end_hour = int(str(today_data_end[0].hour_end_time).split(" ")[1].split(":")[0])

        for i in range(start_hour, end_hour):
            start_times = "0" + str(i) + ":00" if i < 10 else str(i) + ":00"
            end_times = "0" + str(i + 1) + ":00" if i + 1 < 10 else str(i + 1) + ":00"
            one_list = {'time_duan': start_times + " ~ " + end_times, }
            one_dict = {}
            room_list = ["行政楼七楼大会议室", "小会议室", "党员活动室", "内科楼十楼会议室"]
            for t in range(4):
                room_data = ConferenceRoomApplication.objects.filter(
                    hour_statr_time__lte=time.strftime(f"{search_time} {start_times}"),
                    hour_end_time__gte=time.strftime(f"{search_time} {end_times}"),
                    status__in=[1, 2, 0], meeting_root=room_list[t], state='audit')

                if room_data:
                    if str(time.strftime(f"{search_time} {start_times}")) == str(room_data[0].hour_statr_time)[:16]:
                        one_list[f'status_{t}'] = room_data[0].status
                        content_str = "使用科室：" + room_data[0].department + "<br>" + "会议时间：" + \
                                      str(room_data[0].statr_time).split(" ")[1][:-3] + " ~ " + \
                                      str(room_data[0].end_time).split(" ")[1][:-3] + "<br>" + "会议事由：" + room_data[
                                          0].particulars + "<br>" + "参会人数：" + room_data[
                                          0].Number_people + "<br>" + "会议室：" + room_data[0].meeting_root
                        one_list[f'content_{t}'] = content_str
                        one_list[f'merge_{t}'] = int(str(room_data[0].hour_end_time).split(" ")[1].split(":")[0]) - int(str(room_data[0].hour_statr_time).split(" ")[1].split(":")[0])
                else:
                    one_list[f'status_{t}'] = ''
                    one_list[f'content_{t}'] = ''
                    one_list[f'merge_{t}'] = 0
            one_dict['data'] = one_list
            data_list.append(one_dict)
        returnData = {"code": 200, "status": "success", "data": data_list, "message": "操作成功！"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SealMakingDetailViewApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = SealMaking.objects.get(id=id)
        audit_dic = {}
        for audit_obj in obj.sealmakingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {
            'code': 200,
            'message': '数据获取成功！',
            "data": {
                'apply_user': obj.apply_user.real_name, "department": obj.company.name,
                "apply_time": obj.create_time.strftime("%Y-%m-%d %H:%M"), "plan_seal_name": obj.plan_seal_name,
                "making_statue": "初次" if obj.making_number == 1 else "复次", "statue": obj.state,
                "making_number": obj.making_number, "reason": obj.reason,
                'audit_dic': audit_dic, "file_list": file_list,
                'is_audit': 'true' if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
            }
        }
        return HttpResponse(json.dumps(context), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "印章刻制")
        except:
            pass
        obj = SealMaking.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.sealmakingrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.sealmakingrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'two':
            audit_record = obj.sealmakingrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.sealmakingrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'three':
            audit_record = obj.sealmakingrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "印章刻制"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ApplicationSealUseApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = SealApply.objects.get(id=int(id))

        endappave = Staffing.objects.filter(station__in=('印章管理员', '党委印章管理员'))
        end_list = [i.post_personnel.all().first() for i in endappave]

        if int(id) > 782:
            audit_dic = {}
            flow_dict = {}
            for audit_obj in obj.sealapplyauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "file_type": atta_obj.file_type,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

            seal_obj = seal.objects.all()
            leaders_obj = User.objects.filter(group__id=2)
            BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
            try:
                Bstep = audit_dic['B'][-1]['audit_user']
            except:
                Bstep = ''
            dzb_obj = Company.objects.get(id=3).head_people
            sjk_obj = Company.objects.get(id=22).head_people
            flag = 'false'
            for t in main_file_list:
                if t['file_type'] == '1':
                    flag = 'true'

            quick_obj = QuickAuthorization.objects.filter(state='seven', HandledBy=request.user)
            str_list, SealList, JudgmentDictionary = [], [], {}
            if quick_obj.count():
                Quick = 'true'
                for Objs in quick_obj:
                    for i in json.loads(Objs.reason):
                        if seal.objects.get(id=i["yinzhang"]).seal_name not in SealList:
                            SealList.append(seal.objects.get(id=i["yinzhang"]).seal_name)
                        if i['neirong'].strip():
                            str_list.append(i['neirong'].strip())

                        JudgmentDictionary[i['neirong'].strip()] = seal.objects.get(id=i["yinzhang"]).seal_name

            else:
                Quick = 'false'

            copy_obj = MakeCopy.objects.filter(type='a', process_id=int(id))
            copy_flag = 'ture' if copy_obj.count() else 'false'

            if obj.sealapplyauditrecord_set.filter(node="C/D"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="C/D"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["C/D"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="B"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="B"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["B"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="ys"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="ys"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["ys"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="sjk"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="sjk"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["sjk"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="BGS"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="BGS"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["BGS"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="stb"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="stb"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["stb"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="YB"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="YB"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["YB"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="YZ"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="YZ"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["YZ"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="END"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="END"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["END"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="audits"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="audits"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["audits"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="END_2"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="END_2"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["END_2"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

            data_dic = {'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"), 'matter_type_text': obj.matter_type_text,
                        'servings': obj.servings, 'state': obj.get_state_str(), 'seal_name': obj.seal_name, 'credentials': obj.credentials, 'note': obj.note, 'number': obj.number,
                        'audit_dic': audit_dic, 'main_file_list': main_file_list, 'is_edit': 'true' if obj.state == 'six' and obj.apply_user == request.user else 'false', 'Quick': Quick, 'str_list': str_list,
                        'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'seven', 'eight', 'nine', 'eleven', 'twelve'] and request.user in obj.current_audit_users.all() else 'false',
                        'leaders_list': [{"id": tt.id, "real_name": tt.real_name} for tt in leaders_obj], 'Bstep': Bstep, 'sjk_obj': {"real_name": sjk_obj.real_name, 'id': sjk_obj.id},
                        'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'six', 'seven', 'eight', 'nine'] and request.user == obj.apply_user else 'false',
                        'user_obj': [{"real_name": k.real_name, 'id': k.id} for k in User.objects.filter(group_id=1)], 'dzb_obj': {"real_name": dzb_obj.real_name, "id": dzb_obj.id},
                        'uuid': obj.fj_number, 'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                        'flow_dict': flow_dict, "seal_obj": [{"seal_name": j.seal_name, "id": j.id} for j in  seal_obj]}
            return HttpResponse(json.dumps(data_dic), content_type="application/json")
        else:
            audit_dic = {}
            flow_dict = {}
            for audit_obj in obj.sealapplyauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "file_type": atta_obj.file_type,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                     os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

            seal_obj = seal.objects.all()
            BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
            try:
                Bstep = audit_dic['B'][-1]['audit_user']
            except:
                Bstep = ''
            dzb_obj = Company.objects.get(id=3).head_people
            sjk_obj = Company.objects.get(id=22).head_people
            flag = 'false'
            for t in main_file_list:
                if t['file_type'] == '1':
                    flag = 'true'
            category_obj = request.user.quickauthorizationapplicationcategory_set.all()
            category_list = [i.category for i in obj.quick_category.all()]

            copy_obj = MakeCopy.objects.filter(type='a', process_id=int(id))
            copy_flag = 'ture' if copy_obj.count() else 'false'

            if obj.sealapplyauditrecord_set.filter(node="C/D"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="C/D"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["C/D"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="B"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="B"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["B"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                  'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="ys"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="ys"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["ys"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                   'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="BGS"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="BGS"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["BGS"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="sjk"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="sjk"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["sjk"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="stb"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="stb"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["stb"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="YB"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="YB"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["YB"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                   'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="YZ"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="YZ"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["YZ"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                   'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="END"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="END"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["END"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="audits"):
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="audits"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["audits"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                       'sear': len([i for i in flow_dict]) + 1}

            if obj.sealapplyauditrecord_set.filter(node="END_2"):
                print("有这个流程！")
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealapplyauditrecord_set.filter(node="END_2"):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict["END_2"] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                      'sear': len([i for i in flow_dict]) + 1}

            data_dic = {'audit_dic': audit_dic, 'main_file_list': main_file_list, "apply_user": obj.apply_user.real_name, "create_time": obj.create_time.strftime("%Y-%m-%d %H:%M"),
                        'is_edit': 'true' if obj.state == 'six' and obj.apply_user == request.user else 'false', 'matter_type_text': obj.matter_type_text, "servings": obj.servings, "credentials": obj.credentials,
                        'Quick': 'false', 'Bstep': Bstep, 'sjk_obj': {"real_name": sjk_obj.real_name, 'id': sjk_obj.id},
                        'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'seven', 'eight', 'nine'] and request.user in obj.current_audit_users.all() else 'false',
                        'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'six', 'seven', 'eight', 'nine'] and request.user == obj.apply_user else 'false',
                        'user_obj': [{"real_name": i.real_name, "id": i.id} for i in User.objects.filter(group_id=1)], 'dzb_obj': {"real_name": dzb_obj.real_name, "id": dzb_obj.id},
                        'print_flag': 'true' if (request.user in end_list) and obj.state == 'five' else 'flase',
                        'uuid': obj.fj_number, 'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "", 'state': obj.get_state_str(),
                        'flow_dict': flow_dict, "seal_obj": [{"seal_name": j.seal_name, "id": j.id} for j in  seal_obj]}
            return HttpResponse(json.dumps(data_dic), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        leader_id = request.POST.get('leader_id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        cs_people = request.POST.get("cs_people", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "用印审批")
        except:
            pass
        obj = SealApply.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)

        if obj.state == 'one':
            obj.current_audit_users.clear()
            audit_record = obj.sealapplyauditrecord_set.filter(node='C/D', state='unaudit').first()
            if obj.is_fast:
                if obj.authorization_type == '1':  # 法人授权
                    if obj.leval == '1':
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
                        if state == 'audit':
                            obj_state = 'two'
                            obj.current_audit_users.add(next_audit_record.audit_people)
                        else:
                            obj_state = 'six'
                            obj.current_audit_users.add(obj.apply_user)
                    else:
                        TwoSeptObj = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
                        TwoSeptObj.update_time = datetime.now()
                        TwoSeptObj.state = 'audit'
                        TwoSeptObj.save()

                        ThreeSeptObj = obj.sealapplyauditrecord_set.filter(node='ys', state='unaudit').first()
                        ThreeSeptObj.update_time = datetime.now()
                        ThreeSeptObj.state = 'audit'
                        ThreeSeptObj.save()

                        if obj.sealapplyauditrecord_set.filter(node='sjk'):
                            next_audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit').first()
                            obj_state = 'nine'
                        else:
                            next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit').first()
                            obj_state = 'four'

                        if state == 'audit':
                            obj.current_audit_users.add(next_audit_record.audit_people)
                        else:
                            obj_state = 'six'
                            obj.current_audit_users.add(obj.apply_user)
                        MakeCopy.objects.create(recipient=TwoSeptObj.audit_people, process_id=obj.id, type='a')
                        MakeCopy.objects.create(recipient=ThreeSeptObj.audit_people, process_id=obj.id, type='a')

                else:  # 分管授权
                    TwoSeptObj = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
                    TwoSeptObj.update_time = datetime.now()
                    TwoSeptObj.state = 'audit'
                    TwoSeptObj.save()

                    MakeCopy.objects.create(recipient=TwoSeptObj.audit_people, process_id=obj.id, type='a')

                    if obj.sealapplyauditrecord_set.filter(node='sjk'):
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit').first()
                        obj_state = 'nine'
                    else:
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit').first()
                        obj_state = 'four'

                    if state == 'audit':
                        obj.current_audit_users.add(next_audit_record.audit_people)
                    else:
                        obj_state = 'six'
                        obj.current_audit_users.add(obj.apply_user)

            else:
                if state == 'audit':
                    if obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').count():
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
                        obj_state = 'two'
                    else:
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit').first()
                        obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'six'
                    obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            obj.current_audit_users.clear()
            audit_record = obj.sealapplyauditrecord_set.filter(node='B', state='unaudit').first()
            if state == 'audit':
                if obj.is_fast:
                    ThreeSeptObj = obj.sealapplyauditrecord_set.filter(node='ys', state='unaudit').first()
                    ThreeSeptObj.update_time = datetime.now()
                    ThreeSeptObj.state = 'audit'
                    ThreeSeptObj.save()
                    MakeCopy.objects.create(recipient=ThreeSeptObj.audit_people, process_id=obj.id, type='a')

                    if obj.FileType == "1":
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit')
                        obj_state = 'nine'
                    else:
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit')
                        obj_state = 'four'
                else:
                    if obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit'):
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit')
                        obj_state = 'nine'
                    else:
                        next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit')
                        obj_state = 'four'

                for cur in next_audit_record:
                    obj.current_audit_users.add(cur.audit_people)
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            obj.current_audit_users.clear()
            audit_record = obj.sealapplyauditrecord_set.filter(node='YB', state='unaudit').first()
            if state == 'audit':
                dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件', '其他证书']
                sq_list = obj.seal_name.split(', ')
                dw_flag, yb_flag = False, False
                for sq1 in sq_list:
                    if sq1 in dw_list:
                        dw_flag = True
                    if sq1 in yb_list:
                        yb_flag = True
                if yb_flag:
                    BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='END', state='unaudit', audit_people=BGS_appave,
                                                        parent_id=obj)
                    obj.current_audit_users.add(BGS_appave)
                if dw_flag:
                    BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                    SealApplyAuditRecord.objects.create(node='END', state='unaudit', audit_people=BGS_appave,
                                                        parent_id=obj)
                    obj.current_audit_users.add(BGS_appave)

                obj_state = 'eight'
            elif state == "referral":
                for LEADER in leader_id.split(","):
                    leader_obj = User.objects.get(id=int(LEADER))
                    SealApplyAuditRecord.objects.create(node='YZ', state='unaudit', audit_people=leader_obj,
                                                        parent_id=obj)
                    obj.current_audit_users.add(leader_obj)
                obj_state = 'seven'
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            if obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit', audit_people=request.user):
                obj.current_audit_users.remove(request.user)
                audit_record = ""
                audit_step = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit')
                for aud_four in audit_step:
                    if aud_four.audit_people == request.user:
                        audit_record = aud_four
                if state == 'audit':
                    if audit_step.count() == 1:
                        obj_state = 'thirteen'

                        number_list = re.findall('\((.*?)\)', cs_people)
                        dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                        yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件',
                                   '其他证书']
                        sq_list = obj.seal_name.split(', ')
                        for sq1 in sq_list:
                            if sq1 in dw_list:
                                number_list.append(Company.objects.get(id=3).head_people.job_number)
                            if sq1 in yb_list:
                                number_list.append(Company.objects.get(id=80).head_people.job_number)
                        number_list = list(set(number_list))
                        for i in number_list:
                            MakeCopy.objects.create(recipient=User.objects.get(job_number=i), process_id=obj.id)

                        bgs_obj = obj.sealapplyauditrecord_set.filter(node='BGS')
                        for bgs_people in bgs_obj:
                            SealApplyAuditRecord.objects.create(node='thirteen', state='unaudit',
                                                                audit_people=bgs_people.audit_people, parent_id=obj)
                            obj.current_audit_users.add(bgs_people.audit_people)
                    else:
                        obj_state = 'four'
                elif state == "referral":
                    obj.current_audit_users.clear()
                    dz_obj = Company.objects.get(id=3).head_people
                    YbObj = Company.objects.get(id=80).head_people
                    sjk_obj = Company.objects.get(id=22).head_people
                    leader_obj = User.objects.get(id=leader_id)
                    if leader_obj == dz_obj or leader_obj == YbObj:
                        crrt_node = 'YB'
                        obj_state = 'three'
                    elif leader_obj == sjk_obj:
                        crrt_node = 'sjk'
                        obj_state = 'nine'
                    else:
                        crrt_node = 'YZ'
                        obj_state = 'seven'
                    SealApplyAuditRecord.objects.create(node=crrt_node, state='unaudit', audit_people=leader_obj,
                                                        parent_id=obj)
                    obj.current_audit_users.add(leader_obj)
                    for aud_four1 in audit_step:
                        if aud_four1.audit_people != request.user:
                            aud_four1.delete()
                else:
                    obj_state = 'six'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
            else:
                try:
                    audit_record = obj.sealapplyauditrecord_set.filter(audit_people=request.user).first()
                    if state == 'audit':
                        obj_state = 'four'
                    else:
                        obj_state = 'six'
                        obj.current_audit_users.clear()
                        obj.current_audit_users.add(obj.apply_user)
                except:
                    returnData = {'code': 200, 'message': '审核成功！'}
                    return HttpResponse(json.dumps(returnData), content_type="application/json")

        elif obj.state == 'five':
            returnData = {'code': 200, 'message': '上传成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        elif obj.state == 'seven':
            obj.current_audit_users.remove(request.user)
            audit_record = obj.sealapplyauditrecord_set.filter(node='YZ', state='unaudit',
                                                               audit_people=request.user).first()
            if state == 'audit':
                if obj.current_audit_users.all().count():
                    obj_state = "seven"
                else:
                    obj_state = 'eight'
                    dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                    yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件',
                               '其他证书']
                    sq_list = obj.seal_name.split(', ')
                    dw_flag, yb_flag = False, False
                    for sq1 in sq_list:
                        if sq1 in dw_list:
                            dw_flag = True
                        if sq1 in yb_list:
                            yb_flag = True
                    if yb_flag:
                        BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                        SealApplyAuditRecord.objects.create(node='END', state='unaudit', audit_people=BGS_appave,
                                                            parent_id=obj)
                        obj.current_audit_users.add(BGS_appave)
                    if dw_flag:
                        BGS_appave = Staffing.objects.get(station='党委印章管理员').post_personnel.all().first()
                        SealApplyAuditRecord.objects.create(node='END', state='unaudit', audit_people=BGS_appave,
                                                            parent_id=obj)
                        obj.current_audit_users.add(BGS_appave)
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'eight' or obj.state == 'twelve':
            audit_record = ""
            obj.current_audit_users.remove(request.user)
            if obj.state == 'eight':
                audit_step = obj.sealapplyauditrecord_set.filter(node='END', state='unaudit')
            else:
                audit_step = obj.sealapplyauditrecord_set.filter(node='END_2', state='unaudit')
            for foue in audit_step:
                if foue.audit_people == request.user:
                    audit_record = foue
            if state == 'audit':
                if audit_step.count() == 1:
                    obj_state = 'thirteen'

                    number_list = re.findall('\((.*?)\)', cs_people)
                    dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                    yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件',
                               '其他证书']
                    sq_list = obj.seal_name.split(', ')
                    for sq1 in sq_list:
                        if sq1 in dw_list:
                            number_list.append(Company.objects.get(id=3).head_people.job_number)
                        if sq1 in yb_list:
                            number_list.append(Company.objects.get(id=80).head_people.job_number)
                    number_list = list(set(number_list))
                    for i in number_list:
                        MakeCopy.objects.create(recipient=User.objects.get(job_number=i), process_id=obj.id)
                    bgs_obj = obj.sealapplyauditrecord_set.filter(node='BGS')
                    for bgs_people in bgs_obj:
                        SealApplyAuditRecord.objects.create(node='thirteen', state='unaudit',
                                                            audit_people=bgs_people.audit_people, parent_id=obj)
                        obj.current_audit_users.add(bgs_people.audit_people)
                else:
                    obj_state = 'eight'
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'nine' or obj.state == 'eleven':
            obj.current_audit_users.clear()
            if obj.state == 'nine':
                audit_record = obj.sealapplyauditrecord_set.filter(node='sjk', state='unaudit').first()
            else:
                audit_record = obj.sealapplyauditrecord_set.filter(node='audits', state='unaudit').first()

            if state == 'audit':
                if obj.state == 'nine':
                    next_audit_record = obj.sealapplyauditrecord_set.filter(node='BGS', state='unaudit')
                    obj_state = 'four'
                else:
                    next_audit_record = obj.sealapplyauditrecord_set.filter(node='END_2', state='unaudit')
                    obj_state = 'twelve'
                for cur in next_audit_record:
                    obj.current_audit_users.add(cur.audit_people)
            else:
                obj_state = 'six'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'ten':
            obj.current_audit_users.remove(request.user)
            audit_record = ""
            audit_step = obj.sealapplyauditrecord_set.filter(node='stb', state='unaudit')
            for aud_four in audit_step:
                if aud_four.audit_people == request.user:
                    audit_record = aud_four
            if state == 'audit':
                if audit_step.count() == 1:
                    obj_state = 'thirteen'

                    number_list = re.findall('\((.*?)\)', cs_people)
                    dw_list = ['中共京山市人民医院委员会', '党委书记私章', '中国共产主义青年团京山市人民医院总支委员会印章']
                    yb_list = ['京山市人民医院公章', '华中科技大学协和京山医院公章', '法人章', '医疗机构执业许可证(正本)', '事业单位法人证书(正本)', '法人身份证复印件',
                               '其他证书']
                    sq_list = obj.seal_name.split(', ')
                    for sq1 in sq_list:
                        if sq1 in dw_list:
                            number_list.append(Company.objects.get(id=3).head_people.job_number)
                        if sq1 in yb_list:
                            number_list.append(Company.objects.get(id=80).head_people.job_number)
                    number_list = list(set(number_list))
                    for i in number_list:
                        MakeCopy.objects.create(recipient=User.objects.get(job_number=i), process_id=obj.id)
                    bgs_obj = obj.sealapplyauditrecord_set.filter(node='BGS')
                    for bgs_people in bgs_obj:
                        SealApplyAuditRecord.objects.create(node='thirteen', state='unaudit',
                                                            audit_people=bgs_people.audit_people, parent_id=obj)
                        obj.current_audit_users.add(bgs_people.audit_people)
                else:
                    obj_state = 'ten'
            elif state == "referral":
                obj.current_audit_users.clear()
                dz_obj = Company.objects.get(id=3).head_people
                leader_obj = User.objects.get(id=leader_id)
                if leader_obj == dz_obj:
                    crrt_node = 'YB'
                    obj_state = 'three'
                else:
                    crrt_node = 'YZ'
                    obj_state = 'seven'
                SealApplyAuditRecord.objects.create(node=crrt_node, state='unaudit', audit_people=leader_obj,
                                                    parent_id=obj)
                obj.current_audit_users.add(leader_obj)
                for aud_four1 in audit_step:
                    if aud_four1.audit_people != request.user:
                        aud_four1.delete()
            else:
                obj_state = 'six'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'thirteen':
            obj.current_audit_users.remove(request.user)
            audit_record = obj.sealapplyauditrecord_set.filter(node='thirteen', state='unaudit',
                                                               audit_people=request.user).first()
            if state == 'audit':
                if not obj.current_audit_users.all().count():
                    obj_state = 'five'
                    TimeNode = datetime.now().strftime('%Y%m')
                    try:
                        seal_obj = SealApplyNumber.objects.get(time_node=TimeNode)
                        current_number = seal_obj.current_number
                        next_number = seal_obj.next_number
                        seal_obj.current_number = int(current_number) + 1
                        seal_obj.next_number = int(next_number) + 1
                        seal_obj.save()
                    except:
                        current_number = 0  # 当前编号
                        next_number = 1  # 下一个编号（取这个值）
                        SealApplyNumber.objects.create(current_number=current_number + 1, next_number=next_number + 1,
                                                       time_node=TimeNode)

                    current_date = datetime.now().strftime('%Y-%m-%d')
                    current_date_str = current_date.replace('-', '')

                    next_number = "0" + str(next_number) if int(next_number) < 10 else str(next_number)
                    number = 'JYYZ-' + str(current_date_str) + '-' + next_number
                    obj.number = number
                else:
                    obj_state = 'thirteen'
            else:
                obj_state = 'six'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.state = obj_state
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()

        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "用印审批"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.matter_type_text[:15] + "……" if len(obj.matter_type_text) > 15 else obj.matter_type_text
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class QuickAuthorizationApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        seal_obj = seal.objects.all()
        obj = QuickAuthorization.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.quickauthorizationrecord_set.all().order_by("update_time"):
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.quickauthorizationrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        quick_obj = obj.quickauthorizationauthorized_set.all()
        name_list = list(set([i.authorized_person.real_name for i in quick_obj]))
        seal_list = [{"id": t.id, "seal_name": t.seal_name} for t in seal_obj]
        context = {
            'code': 200, 'message': '成功',
            "data": {
                'audit_dic': audit_dic, "seal_obj": seal_list,
                'seal_list': [i.id for i in obj.seal_name.all()],
                'seal_name': ', '.join([i.seal_name for i in obj.seal_name.all()]),
                'reason': json.loads(obj.reason),
                'is_audit': 'true' if obj.state in ['one',
                                                    'two'] and request.user in obj.current_audit_users.all() else 'false',
                "name_list": ", ".join(name_list),
                'is_stop': 'true' if obj.state in ['one', 'two'] and request.user == obj.apply_user else 'false',
                'flow_dict': flow_dict, "apply_user": obj.apply_user.real_name, "company": obj.company.name
            }
        }
        return HttpResponse(json.dumps(context), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过

        obj = QuickAuthorization.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        if obj.state == 'one':
            audit_list = obj.quickauthorizationrecord_set.filter(node='one', state='unaudit')
            audit_record = None
            for ii in audit_list:
                if ii.audit_people == request.user:
                    audit_record = ii
            if state == 'audit':
                if audit_list.count() == 1:
                    obj.current_audit_users.clear()
                    next_audit_record = obj.quickauthorizationrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'one'
                    obj.current_audit_users.remove(request.user)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            obj.current_audit_users.clear()
            audit_record = obj.quickauthorizationrecord_set.filter(node='two', state='unaudit').first()
            obj_state = 'seven'
            this_flow_seal = obj.seal_name.all()
            audit_people_list = re.findall('\((.*?)\)', state)
            audit_people_objs = User.objects.filter(job_number__in=audit_people_list)

            for us in audit_people_objs:
                for i in json.loads(obj.reason):
                    for tt in i['neirong'].split("\n"):
                        if tt.strip():
                            QuickAuthorizationApplicationCategory.objects.create(authorized_person=us, category=tt.split('、')[1], seal_id=seal.objects.get(id=int(i['yinzhang'])))
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                MakeCopy.objects.create(recipient=BGS_appave, process_id=obj.id, type='c')
            state = 'audit'
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        if audit_record:
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()
        returnDict = {'code': 200, 'message': '审批成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProcessManagement(LoginRequiredMixin, View):
    def post(self, request):
        user_id = request.user.id
        user_name = request.user.real_name
        department = request.user.company.name
        need_do = sum([i[2] for i in sql_file.manage_flow().my_audit(user_id, user_name)])
        Completed = sum([i[2] for i in sql_file.manage_flow().my_done(user_id, user_name)])
        apply = sum([i[2] for i in sql_file.manage_flow().my_apply(user_id, user_name, department)])
        returnDict = {'code': 200, 'message': 'success!', 'data': [{'need_do': need_do, "completed": Completed, "apply": apply}]}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ContractPaymentApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        try:
            cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        except:
            returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj = LogisticsOffice.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.logisticsofficeauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.logisticsofficeauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {"apply_user": obj.apply_user.real_name, 'company': obj.company.name, 'pay_reason': obj.pay_reason, 'note': obj.note, "payee": obj.payee, "payee_account": obj.payee_account,
                   'audit_dic': audit_dic, "file_list": file_list, "total_money": obj.total_money, "daxie": obj.daxie, "BankDeposit": obj.BankDeposit, "rask": obj.rask,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six", "zero"] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', "zero", "eight"] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "合同付款")
        except:
            pass
        obj = LogisticsOffice.objects.get(id=int(id))
        obj.current_audit_users.clear()
        obj.audit_users_already.add(request.user)
        if obj.state == 'zero':
            if state == 'audit':
                audit_record = None
                audit_list = obj.logisticsofficeauditrecord_set.filter(node='zero', state='unaudit')
                for zero in audit_list:
                    if request.user == zero.audit_people:
                        audit_record = zero
                if obj.logisticsofficeauditrecord_set.filter(node='one'):
                    obj_state = 'one'
                    next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='one', state='unaudit').first()
                else:
                    obj_state = 'two'
                    next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='two', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'one':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='one', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'two':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='two', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'three':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='three', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'four':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='four', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'five':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='five', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'six':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "合同付款"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class FixedAssetsApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get("id", None)
        revise = request.GET.get("revise", '')
        obj = FixedAssets.objects.get(id=id)
        audit_dic = {}
        flow_dict = {}
        for audit_obj in obj.fixedassetsauditrecord_set.all().order_by("update_time"):
            node = "科室负责人" if audit_obj.node == 'SBKZ' else "分管领导" if audit_obj.node == 'B' else "负责人" if audit_obj.node == 'SJ/YZ' else "财务科长" if audit_obj.node == 'CWKZ' else "财务支付"
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.fixedassetsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1, "node": node}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {"apply_user": obj.apply_user.real_name, "company": obj.company.name, "title": obj.title, "financial": obj.financial, "payee": obj.payee, "payee_account": obj.payee_account,
                   "remake": obj.remake, "total_money": obj.total_money, "daxie": obj.daxie,
                   'audit_dic': audit_dic, "file_list": file_list,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', ] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'seven'] and request.user == obj.apply_user else 'false',
                   'detail_pay': json.loads(obj.detail_pay),
                   'flow_dict': flow_dict,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "固定资产/维修维保付款")
        except:
            pass
        obj = FixedAssets.objects.get(id=int(id))
        obj.current_audit_users.clear()
        obj.audit_users_already.add(request.user)
        if obj.state == 'one':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='SBKZ', state='unaudit').first()
            if obj.fixedassetsauditrecord_set.filter(node='B', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='B', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'three'
            elif obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'two'
            elif obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'four'
            elif obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'five'
            else:
                next_node = 'six'

            if state == 'audit':
                obj_state = next_node
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit').first()
            if obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'four'
            elif obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'five'
            else:
                next_node = 'six'
            if state == 'audit':
                obj_state = next_node
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='B', state='unaudit').first()
            if obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWKZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'two'
            elif obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'four'
            elif obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'five'
            else:
                next_node = 'six'

            if state == 'audit':
                obj_state = next_node
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
            if obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit'):
                next_audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
                next_node = 'five'
            else:
                next_node = 'six'
            if state == 'audit':
                obj_state = next_node
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.fixedassetsauditrecord_set.filter(node='CWK', state='unaudit').first()
            if state == 'audit':
                obj_state = 'six'
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "资产维保"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MaterialPaymentApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = MedicalMaterials.objects.get(id=id)
        fujian_obj = Topicsattachments.objects.filter(topics_number=obj.fj_number)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.medicalmaterialsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.medicalmaterialsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in fujian_obj]
        record_file_list = [atta_obj.pdf_path.replace("\\", "/") for atta_obj in Topicsattachments.objects.filter(topics_number=obj.medicalmaterialsauditrecord_set.get(node='six').audit_note)]
        context = {'apply_user': obj.apply_user.real_name, 'company': obj.company.name, "title": obj.title, "source": obj.source, "payee": obj.payee, "payee_account": obj.payee_account,
                   'accounting': obj.accounting, "accounting_list": [{'id': "515", "real_name": "徐亚红"}, {'id': "850", "real_name": "姚丽娥"}, {'id': "781", "real_name": "陈伊妮"}],
                   'remake': obj.remake, 'total_amount': obj.total_amount, 'daxie': obj.daxie,
                   'file_list': file_list, "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   "detail_pay": json.loads(obj.detail_pay),
                   'file_path': fujian_obj.first().pdf_path.replace("\\", "/") if fujian_obj else "",
                   'flow_dict': flow_dict
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "材料付款")
        except:
            pass
        obj = MedicalMaterials.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='one', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='two', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                if obj.medicalmaterialsauditrecord_set.filter(node='one', state='unaudit'):
                    next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='one', state='unaudit').first()
                    obj_state = 'one'
                else:
                    next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='three', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'eight'
        elif obj.state == 'four':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='four', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
            else:
                obj_state = 'eight'
        elif obj.state == 'five':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='five', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
            else:
                obj_state = 'eight'
        elif obj.state == 'six':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='six', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "材料付款"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MealSupplementPaymentApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = NutritionalMeals.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.nutritionalmealsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.nutritionalmealsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        leaders_list = User.objects.filter(group__id=2)
        context = {'apply_user': obj.apply_user.real_name, "company": obj.company.name, "type": obj.type, "source": obj.source, "payee": obj.payee, "account": obj.account,
                   'DemandDepartment': obj.DemandDepartment, 'title': obj.title, 'total_amount': obj.total_amount, "daxie": obj.daxie,
                   'file_list': file_list, "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   "detail_pay": json.loads(json.loads(obj.detail_pay)),
                   "leaders_list": [{"id": tt.id, "real_name": tt.real_name} for tt in leaders_list],
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "餐补付款")
        except:
            pass
        obj = NutritionalMeals.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='one', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                if obj.nutritionalmealsauditrecord_set.filter(node='two'):
                    next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='two', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='three', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                if obj.nutritionalmealsauditrecord_set.filter(node='four'):
                    next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                else:
                    next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
            else:
                obj_state = 'eight'
        elif obj.state == 'four':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='four', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
            else:
                obj_state = 'eight'
        elif obj.state == 'five':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='five', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
            else:
                obj_state = 'eight'
        elif obj.state == 'six':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='six', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "餐补付款"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SubjectFundingApprovalApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = SubjectFunding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.subjectfundingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.subjectfundingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {"apply_user": obj.apply_user.real_name, 'company': obj.company.name, 'pay_reason': obj.pay_reason, 'rask': obj.rask,
                   'total_money': obj.total_money, 'daxie': obj.daxie, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'eight'] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise, "pay_detail": json.loads(obj.pay_detail),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace( "\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "学科经费")
        except:
            pass
        obj = SubjectFunding.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.subjectfundingrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.subjectfundingrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.subjectfundingrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.subjectfundingrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.subjectfundingrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.subjectfundingrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.subjectfundingrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.subjectfundingrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.subjectfundingrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                if obj.subjectfundingrecord_set.filter(node='six'):
                    next_audit_record = obj.subjectfundingrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'seven'
                    if obj.people_type == "1":
                        try:
                            headers = {
                                "Content-Type": 'application/json'
                            }
                            for rson in json.loads(obj.pay_detail):
                                post_data = {
                                    'key': 'hOJYdf7WoMTZV06Q',
                                    'department_name': obj.company.name,
                                    'time': obj.create_time.strftime("%Y-%m-%d"),
                                    'amount': float(rson['budget_amount'].replace(",", '')) / 10000,
                                    'agent_name': obj.apply_user.real_name,
                                    'reason': rson['goods_name']
                                }
                                req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                                print(req.text)
                        except:
                            print("同步更新出错")
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.subjectfundingrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
                if obj.people_type == "1":
                    try:
                        headers = {
                            "Content-Type": 'application/json'
                        }
                        for rson in json.loads(obj.pay_detail):
                            post_data = {
                                'key': 'hOJYdf7WoMTZV06Q',
                                'department_name': obj.company.name,
                                'time': obj.create_time.strftime("%Y-%m-%d"),
                                'amount': float(rson['budget_amount'].replace(",", '')) / 10000,
                                'agent_name': obj.apply_user.real_name,
                                'reason': rson['goods_name']
                            }
                            req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                            print(req.text)
                    except:
                        print("同步更新出错")
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "学科经费"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 科研经费申请详情&审批
class ResearchFundingApprovalApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ResearchFunding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.researchfundingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.researchfundingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'apply_user': obj.apply_user.real_name, 'company': obj.company.name, "pay_reason": obj.pay_reason, "people_type": "临床医技人员" if obj.people_type == "1" else "行管人员",
                   'rask': obj.rask, 'payee': obj.payee, 'account_number': obj.account_number, 'total_money': obj.total_money, 'daxie': obj.daxie, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise, "pay_detail": json.loads(obj.pay_detail),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace( "\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "科研经费")
        except:
            pass
        obj = ResearchFunding.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.researchfundingrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.researchfundingrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.researchfundingrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.researchfundingrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.researchfundingrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.researchfundingrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
                if obj.people_type == "1":
                    try:
                        headers = {
                            "Content-Type": 'application/json'
                        }
                        for rson in json.loads(obj.pay_detail):
                            post_data = {
                                'key': 'hOJYdf7WoMTZV06Q',
                                'department_name': obj.company.name,
                                'time': obj.create_time.strftime("%Y-%m-%d"),
                                'amount': float(rson['budget_amount'].replace(",", '')) / 10000,
                                'agent_name': obj.apply_user.real_name,
                                'reason': rson['goods_name']
                            }
                            req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                            print(req.text)
                    except:
                        print("同步更新出错")

            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "科研经费"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class TradeUnionOutlaysApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = LaborUnionExpenses.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.laborunionexpensesrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.laborunionexpensesrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {"apply_user": obj.apply_user.real_name, 'company': obj.company.name, 'pay_reason': obj.pay_reason, 'pay_type': obj.pay_type, 'payee': obj.payee,
                   'payee_account': obj.payee_account, 'total_money': obj.total_money, 'daxie': obj.daxie, 'BankDeposit': obj.BankDeposit,
                   'rask': obj.rask, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six", "nine"] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', "nine"] and request.user == obj.apply_user else 'false', 'flow_dict': flow_dict,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会经费")
        except:
            pass
        obj = LaborUnionExpenses.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.laborunionexpensesrecord_set.filter(node='two'):
                    next_audit_record_list = obj.laborunionexpensesrecord_set.filter(node='two', state='unaudit')
                    obj_state = 'two'
                    for next in next_audit_record_list:
                        next.state = 'audit'
                        next.save()
                        obj.current_audit_users.add(next.audit_people)
                elif obj.laborunionexpensesrecord_set.filter(node='three'):
                    next_audit_record = obj.laborunionexpensesrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    next_audit_record = obj.laborunionexpensesrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = None
            if state == 'audit':
                audit_list = obj.laborunionexpensesrecord_set.filter(node='two', state='unaudit')
                for zero in audit_list:
                    if request.user == zero.audit_people:
                        audit_record = zero
                next_audit_record = obj.laborunionexpensesrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='three', state='unaudit').first()
            next_audit_record = obj.laborunionexpensesrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='four', state='unaudit').first()
            next_audit_record = obj.laborunionexpensesrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='five', state='unaudit').first()
            next_audit_record = obj.laborunionexpensesrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='six', state='unaudit').first()
            next_audit_record = obj.laborunionexpensesrecord_set.filter(node='nine', state='unaudit').first()
            if state == 'audit':
                obj_state = 'nine'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'nine':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='nine', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "工会经费"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class GeneralPaymentApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = GeneralFinance.objects.get(id=id)
        revise = request.GET.get('revise', None)
        fujian_obj = Topicsattachments.objects.filter(topics_number=obj.fj_number)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.generalfinanceauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.generalfinanceauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in fujian_obj]

        context = {'apply_user': obj.apply_user.real_name, 'company': obj.company.name, 'title': obj.title, 'payee': obj.payee, 'payee_account': obj.payee_account, 'daxie': obj.daxie,
                   'remake': obj.remake, 'total_amount': obj.total_amount, 'file_list': file_list, "detail_pay": json.loads(json.loads(obj.detail_pay)), "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'eight'] and request.user == obj.apply_user else 'false',
                   'file_path': fujian_obj.first().pdf_path.replace("\\", "/") if fujian_obj else "", 'flow_dict': flow_dict
                }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "一般付款")
        except:
            pass
        obj = GeneralFinance.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='one', state='unaudit',
                                                                 audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.generalfinanceauditrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='two', state='unaudit',
                                                                 audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.generalfinanceauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='three', state='unaudit',
                                                                 audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.generalfinanceauditrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'eight'
        elif obj.state == 'four':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='four', state='unaudit',
                                                                 audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.generalfinanceauditrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
            else:
                obj_state = 'eight'
        elif obj.state == 'five':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='five', state='unaudit',
                                                                 audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        obj.can_revise = '0'
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "一般付款"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NewspaperPaymentApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = BookSubscription.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.booksubscriptionrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.booksubscriptionrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        context = {"apply_user": obj.apply_user.real_name, 'company': obj.company.name,
                   'audit_dic': audit_dic, 'reason': json.loads(obj.reason), 'book_buy': json.loads(obj.book_buy),
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user == obj.apply_user else 'false', 'flow_dict': flow_dict
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "图书/报刊/杂志征订")
        except:
            pass
        obj = BookSubscription.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.booksubscriptionrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.booksubscriptionrecord_set.filter(node='two', state='unaudit')
                obj_state = 'two'
                for i in next_audit_record:
                    obj.current_audit_users.add(i.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.booksubscriptionrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.booksubscriptionrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
            obj.booksubscriptionrecord_set.filter(~Q(audit_people=request.user), node='two', state='unaudit').delete()

        elif obj.state == 'three':
            audit_record = obj.booksubscriptionrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.booksubscriptionrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.booksubscriptionrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "后勤管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = "图书/报刊/杂志征订"
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审批成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TravelApplicationApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = TravelApply.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.travelapplyauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        one_step = obj.travelapplyauditrecord_set.filter(node='one')
        if one_step:
            apply_people = []
            apply = 'true'
            for obj_s in one_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['one'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        four_step = obj.travelapplyauditrecord_set.filter(node='two')
        if four_step:
            apply_people = []
            apply = 'true'
            for obj_s in four_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['two'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        two_step = obj.travelapplyauditrecord_set.filter(node='three')
        if two_step:
            apply_people = []
            apply = 'true'
            for obj_s in two_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['three'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        three_step = obj.travelapplyauditrecord_set.filter(node='four')
        if three_step:
            apply_people = []
            apply = 'true'
            for obj_s in three_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['four'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        context = {'apply_user': obj.apply_user.real_name, 'company': obj.company.name, 'start_time': obj.start_time.split(' ')[0], 'end_time': obj.end_time.split(' ')[0], 'travel_type': obj.travel_type,
                   'route' : obj.route, 'subject': obj.subject, 'travel_users': ', '.join([i.real_name for i in obj.travel_users.all()]), 'note': obj.note, 'file_list': file_list, "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user == obj.apply_user else 'false',
                   "flow_dict": flow_dict, "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""}
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        obj = TravelApply.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "差旅申请")
        except:
            pass
        if int(id) < 260:
            if obj.state == 'one':
                obj.current_audit_users.clear()
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='one',
                                                                  audit_people=request.user).first()

                if state == 'audit':
                    countersign_list = obj.travelapplyauditrecord_set.filter(state='unaudit',
                                                                             node__in=['six', 'seven', 'eight', 'nine'])
                    if countersign_list.count():
                        obj_state = 'six'
                        for tt in countersign_list:
                            if audit_obj.audit_people != tt.audit_people:
                                obj.current_audit_users.add(tt.audit_people)
                            else:
                                tt.update_time = datetime.now()
                                tt.state = state
                                tt.audit_note = audit_note
                                tt.save()

                    else:
                        obj_state = 'two'
                        next_audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two').first()
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                    obj.state = obj_state
                    obj.save()
                else:
                    obj_state = 'four'
                    obj.state = obj_state
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()
                audit_obj.update_time = datetime.now()
                audit_obj.state = state
                audit_obj.audit_note = audit_note
                audit_obj.save()
                obj.can_revise = '0'
                obj.save()
                # ********************************************** 发送小程序推送 ******************************************
                topic_type = "差旅申请"
                applicant = obj.apply_user.real_name
                ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
                SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
                for jj in obj.current_audit_users.all():
                    try:
                        RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '审核成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            elif obj.state == 'two':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two',
                                                                  audit_people=request.user).first()
                obj.current_audit_users.clear()
                if state == 'audit':
                    next_audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three').first()
                    if next_audit_obj:
                        obj_state = 'three'
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                    else:
                        obj_state = 'five'
                    obj.state = obj_state
                    obj.save()
                else:
                    obj_state = 'four'
                    obj.state = obj_state
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()
                audit_obj.update_time = datetime.now()
                audit_obj.state = state
                audit_obj.audit_note = audit_note
                audit_obj.save()
                obj.can_revise = '0'
                obj.save()
                # ********************************************** 发送小程序推送 ******************************************
                topic_type = "差旅申请"
                applicant = obj.apply_user.real_name
                ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
                SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
                for jj in obj.current_audit_users.all():
                    try:
                        RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '审核成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            elif obj.state == 'three':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three',
                                                                  audit_people=request.user).first()
                obj.current_audit_users.clear()
                if state == 'audit':
                    obj.state = 'five'
                    obj.save()
                else:
                    obj_state = 'four'
                    obj.state = obj_state
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()
                audit_obj.update_time = datetime.now()
                audit_obj.state = state
                audit_obj.audit_note = audit_note
                audit_obj.save()
                obj.can_revise = '0'
                obj.save()
                returnDict = {'code': 200, 'message': '审核成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            elif obj.state in ['six', 'seven', 'eight', 'nine']:
                if state == 'audit':
                    if obj.current_audit_users.count() == 1:
                        obj.current_audit_users.clear()
                        obj.state = 'two'
                        obj.save()
                        next_audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two').first()
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                    else:
                        obj.current_audit_users.remove(request.user)
                else:
                    obj.state = 'four'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()
                audit_list = obj.travelapplyauditrecord_set.filter(state='unaudit',
                                                                   node__in=['six', 'seven', 'eight', 'nine'])
                for ia in audit_list:
                    if ia.audit_people == request.user:
                        ia.update_time = datetime.now()
                        ia.state = state
                        ia.audit_note = audit_note
                        ia.save()
                obj.can_revise = '0'
                obj.save()
                # ********************************************** 发送小程序推送 ******************************************
                topic_type = "差旅申请"
                applicant = obj.apply_user.real_name
                ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
                SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
                for jj in obj.current_audit_users.all():
                    try:
                        RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '审核成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            if obj.state == 'one':
                obj.current_audit_users.clear()
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='one',
                                                                  audit_people=request.user).first()
                if state == 'audit':
                    two_step_list = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two')
                    three_step_list = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three')
                    if two_step_list:
                        obj_state = 'two'
                        for two_step in two_step_list:
                            obj.current_audit_users.add(two_step.audit_people)
                    elif three_step_list:
                        obj_state = 'three'
                        for three_step in three_step_list:
                            obj.current_audit_users.add(three_step.audit_people)
                    else:
                        obj_state = 'four'
                        next_audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four').first()
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                    obj.state = obj_state
                    obj.save()
                else:
                    obj.state = 'eight'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()

            elif obj.state == 'two':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two',
                                                                  audit_people=request.user).first()
                obj.current_audit_users.clear()
                if state == 'audit':
                    three_step_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three')
                    if three_step_obj:
                        obj_state = 'three'
                        for three_step in three_step_obj:
                            if three_step.audit_people == request.user:
                                three_step.update_time = datetime.now()
                                three_step.state = state
                                three_step.audit_note = audit_note
                                three_step.save()
                            else:
                                obj.current_audit_users.add(three_step.audit_people)

                        if not obj.travelapplyauditrecord_set.filter(state='unaudit', node='three'):
                            obj_state = 'four'
                            four_step_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four').first()
                            obj.current_audit_users.add(four_step_obj.audit_people)

                    else:
                        obj_state = 'four'
                        four_step_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four').first()
                        obj.current_audit_users.add(four_step_obj.audit_people)
                    obj.state = obj_state
                    obj.save()
                else:
                    obj.state = 'eight'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()

            elif obj.state == 'three':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three',
                                                                  audit_people=request.user).first()
                if state == 'audit':
                    obj.current_audit_users.remove(request.user)
                    if obj.current_audit_users.all().count():
                        obj_state = 'three'
                    else:
                        obj_state = 'four'
                        four_step_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four').first()
                        obj.current_audit_users.add(four_step_obj.audit_people)
                    obj.state = obj_state
                    obj.save()
                else:
                    obj.state = 'eight'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()

            elif obj.state == 'four':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four',
                                                                  audit_people=request.user).first()
                obj.current_audit_users.clear()
                if state == 'audit':
                    obj.state = "five"
                    obj.save()
                else:
                    obj.state = 'eight'
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()

            else:
                returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            audit_obj.update_time = datetime.now()
            audit_obj.state = state
            audit_obj.audit_note = audit_note
            audit_obj.save()
            obj.can_revise = '0'
            obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "差旅申请"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
            returnDict = {'code': 200, 'message': '审核成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TravelReimbursementApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        trave_id = request.GET.get("id", None)
        revise = request.GET.get("revise", None)
        two_audit_people = Staffing.objects.get(station="财务出纳").post_personnel.all().first()
        if int(trave_id) > 58:
            trave_obj = TravelReimbursement.objects.get(id=int(trave_id))
            travel_people_list = [i.real_name for i in trave_obj.travel_people.all().order_by("id")]
            if trave_obj.id == 134:
                OnePeople = travel_people_list[0]
                travel_people_list.remove("陈勇")
                travel_people_list[0] = travel_people_list[1]
                travel_people_list[1] = OnePeople
                travel_people_list.insert(-1, '陈勇')
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                     os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=trave_obj.uuid)]
            audit_dic, flow_dict = {}, {}
            for audit_obj in trave_obj.travelreimbursementauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    if audit_obj.node != 'two':
                        if audit_obj.state != "unaudit":
                            audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                          'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                    else:
                        audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                          'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                          'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in trave_obj.travelreimbursementauditrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                                 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                  'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            if 'two' in audit_dic and len(audit_dic['two']) > 2:
                audit_dic['two'] = audit_dic['two'][-2:]

            SourceFunds = "学科经费" if trave_obj.SourceFunds == '1' else "公卫经费" if trave_obj.SourceFunds == '2' else "自有经费"
            context = {'apply_user': trave_obj.applicat.real_name, "company": trave_obj.applicat.company.name, 'uuid': trave_obj.uuid, 'file_list': file_list,
                       'apply_time': trave_obj.apply_time, "travel_people": ", ".join(travel_people_list),
                       "vote_reluse": trave_obj.vote_reluse,
                       "total_daxie": trave_obj.total_daxie, 'business_days': trave_obj.business_days,
                       'hotel_expense': trave_obj.hotel_expense,
                       'business_matter': trave_obj.business_matter, 'traffic_expense': trave_obj.traffic_expense,
                       'payee': trave_obj.payee, 'remarks': trave_obj.remarks, 'total': trave_obj.total,
                       'TotalList': json.loads(json.loads(trave_obj.reimburse_dict))['TotalList'],
                       'OtherList': json.loads(json.loads(trave_obj.reimburse_dict))['OtherList'], 'sp_company': trave_obj.AuditDepartment,
                       "audit_dic": audit_dic, 'SourceFunds': SourceFunds, 'relevance': {'id': trave_obj.relevance.id, 'title': trave_obj.relevance.subject} if trave_obj.relevance else {},
                       'relevance_car': {"id": trave_obj.relevance_car.id, "title": trave_obj.relevance_car.subject} if trave_obj.relevance_car else {}, 'relevance_zc': {"id": trave_obj.relevance_zc.id, "title": trave_obj.relevance_zc.title} if trave_obj.relevance_zc else {},
                       "is_audit": "true" if trave_obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine'] and request.user in trave_obj.current_audit_users.all() else 'false',
                       "is_stop": "true" if trave_obj.state == 'two' and request.user == two_audit_people else 'false', "id": trave_id, "flow_dict": flow_dict,
                       "file_path": Topicsattachments.objects.filter(topics_number=trave_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=trave_obj.uuid) else ""}
            returnDict = {'code': 200, 'message': 'success', 'data': context}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            trave_obj = TravelReimbursement.objects.get(id=int(trave_id))
            data_obj = {'apply_time': trave_obj.apply_time, "travel_people": ", ".join([i.real_name for i in trave_obj.travel_people.all()]),
                        "vote_reluse": trave_obj.vote_reluse, "total_daxie": trave_obj.total_daxie, 'business_days': trave_obj.business_days,
                        'hotel_expense': trave_obj.hotel_expense, 'business_matter': trave_obj.business_matter, 'traffic_expense': trave_obj.traffic_expense,
                        'payee': trave_obj.payee, 'remarks': trave_obj.remarks, 'reimburse_dict': json.loads(json.loads(trave_obj.reimburse_dict)),
                        'total': trave_obj.total, 'is_edit': 'true' if trave_obj.get_state_str() == '拒绝' else 'false'}
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=trave_obj.uuid)]
            audit_dic, flow_dict = {}, {}
            for audit_obj in trave_obj.travelreimbursementauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    if audit_obj.state != "unaudit":
                        audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                      'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in trave_obj.travelreimbursementauditrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                  'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}
                                                 ]

            payment_obj = ['data:image/jpeg;base64,' + i.imgs.replace(" ", "+") for i in trave_obj.travelreimbursementpayment_set.all()]
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                       'apply': trave_obj.applicat.real_name,
                       "company": trave_obj.applicat.company.name, 'uuid': trave_obj.uuid, 'file_list': file_list,
                       'data_obj': data_obj, "audit_dic": audit_dic,
                       "is_audit": "true" if trave_obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine'] and request.user in trave_obj.current_audit_users.all() else 'false',
                       "is_stop": "true" if trave_obj.state == 'two' and request.user == two_audit_people else 'false',
                       "payment_obj": payment_obj,
                       "id": trave_id, "trave_obj": trave_obj, "flow_dict": flow_dict, "revise": revise,
                       "file_path": Topicsattachments.objects.filter(topics_number=trave_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(
                           topics_number=trave_obj.uuid) else ""}
            returnDict = {'code': 200, 'message': 'success', 'data': context}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        ReimbursementAmount = request.POST.get("ReimbursementAmount", '')  # 实际报销金额

        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "差旅报销")
        except:
            pass

        obj = TravelReimbursement.objects.get(id=int(id))
        obj.current_audit_users.clear()

        if obj.state == 'one':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="two", state='unaudit').first()
                obj_state = "two"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'nine':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='nine', state='unaudit').first()
            if state == 'audit':
                if obj.travelreimbursementauditrecord_set.filter(node='two', state='unaudit'):
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="two",
                                                                                      state='unaudit').first()
                    obj_state = "two"
                else:
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="three",
                                                                                      state='unaudit').first()
                    obj_state = "three"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'two':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                if obj.travelreimbursementauditrecord_set.filter(node='nine', state='unaudit'):
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="nine",
                                                                                      state='unaudit').first()
                    obj_state = "nine"
                else:
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="three",
                                                                                      state='unaudit').first()
                    obj_state = "three"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'three':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="four", state='unaudit').first()
                obj_state = "four"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'four':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                if obj.travelreimbursementauditrecord_set.filter(node="five", state='unaudit'):
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="five",
                                                                                      state='unaudit').first()
                    obj_state = "five"
                else:
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="six",
                                                                                      state='unaudit').first()
                    obj_state = "six"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'five':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="six", state='unaudit').first()
                obj_state = "six"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)

        elif obj.state == 'six':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = "seven"
                try:
                    if obj.SourceFunds == '1':
                        headers = {
                            "Content-Type": 'application/json'
                        }
                        post_data = {
                            'key': 'hOJYdf7WoMTZV06Q',
                            'department_name': obj.company.name,
                            'time': obj.create_time.strftime("%Y-%m-%d"),
                            'amount': float(ReimbursementAmount.replace(",", '')) / 10000,
                            'agent_name': obj.applicat.real_name,
                            'reason': obj.business_matter
                        }
                        req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                        print(req.text)
                except:
                    print("同步更新出错")
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)

        else:
            returnData = {'code': 400, 'message': '流程状态出错了！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()

        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "差旅报销"
        applicant = obj.applicat.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.business_matter[:15] + "……" if len(obj.business_matter) > 15 else obj.business_matter
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MiddleLevelOutApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        outgoing_id = request.GET.get("id", None)
        revise = request.GET.get("revise", '')
        outgoing_obj = OutgoingCadresData.objects.get(id=int(outgoing_id))
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in outgoing_obj.outgoingcadresdatarecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in outgoing_obj.outgoingcadresdatarecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'apply_user': outgoing_obj.apply_user.real_name, "company": outgoing_obj.company.name, 'create_time': outgoing_obj.create_time.strftime("%Y-%m-%d"),
                   'outgoing_person': ', '.join([i.real_name for i in outgoing_obj.outgoing_person.all()]), 'duties': outgoing_obj.duties, 'start_time': outgoing_obj.start_time.split(' ')[0],
                   'end_time': outgoing_obj.end_time.split(' ')[0], 'destination': outgoing_obj.destination, 'department_charge': outgoing_obj.department_charge.id if outgoing_obj.department_charge else "",
                   'file_list': file_list, "audit_dic": audit_dic, 'title': outgoing_obj.title,
                   "is_audit": "true" if outgoing_obj.state in ['one', 'two', 'three'] and request.user in outgoing_obj.current_audit_users.all() else 'false',
                   "is_stop": "true" if outgoing_obj.state in ['one', 'two', 'three', 'eight'] and request.user == outgoing_obj.apply_user else 'false', "flow_dict": flow_dict,
                   "file_path": Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid) else ""}
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        outgoing_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "中层干部外出")
        except:
            pass
        outgoing_obj = OutgoingCadresData.objects.get(id=int(outgoing_id))

        if outgoing_obj.state == 'one':
            audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='one', state='unaudit').first()
            next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='two', state='unaudit').first()
            outgoing_obj.current_audit_users.clear()
            if state == 'audit':
                obj_state = 'two'
                outgoing_obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                outgoing_obj.current_audit_users.add(outgoing_obj.apply_user)
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()
        elif outgoing_obj.state == 'two':
            audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='two', state='unaudit').first()
            outgoing_obj.current_audit_users.clear()
            if state == 'audit':
                four_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='four', state='unaudit')
                if four_record:
                    this_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='four', state='unaudit').first()
                    one_node = outgoing_obj.outgoingcadresdatarecord_set.filter(node='one',
                                                                                audit_people=this_record.audit_people)
                    if one_node:
                        this_record.update_time = datetime.now()
                        this_record.state = one_node.last().state
                        this_record.audit_note = one_node.last().audit_note
                        this_record.save()
                        next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='three',
                                                                                             state='unaudit').first()
                        this_status = 'three'
                    else:
                        next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='four',
                                                                                             state='unaudit').first()
                        this_status = 'four'
                else:
                    next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='three',
                                                                                         state='unaudit').first()
                    this_status = 'three'
                obj_state = this_status
                outgoing_obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                outgoing_obj.current_audit_users.add(outgoing_obj.apply_user)
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()

        elif outgoing_obj.state == 'four':
            audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='four', state='unaudit').first()
            next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='three', state='unaudit').first()
            outgoing_obj.current_audit_users.clear()
            if state == 'audit':
                obj_state = 'three'
                outgoing_obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                outgoing_obj.current_audit_users.add(outgoing_obj.apply_user)
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()

        else:
            audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='three', state='unaudit').first()
            outgoing_obj.current_audit_users.clear()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                outgoing_obj.current_audit_users.add(outgoing_obj.apply_user)
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()
        outgoing_obj.audit_users_already.add(request.user)
        outgoing_obj.state = obj_state
        outgoing_obj.can_revise = "0"
        outgoing_obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "干部外出"
        applicant = outgoing_obj.apply_user.real_name
        ApplicationTime = outgoing_obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = outgoing_obj.title[:15] + "……" if len(outgoing_obj.title) > 15 else outgoing_obj.title
        for jj in outgoing_obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class AskLeaveApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        id = request.GET.get("id", None)
        obj = LeaveRequest.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.leaverequestauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.leaverequestauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'apply_user': obj.apply_user.real_name, 'job_num': obj.job_num, "company": obj.company.name, "start_time": obj.start_time, "end_time": obj.end_time,
                   "reason": obj.reason, 'audit_dic': audit_dic, "file_list": file_list, "leave_type": obj.get_leave_type(),
                   'is_edit': 'true' if obj.state == 'eight' and obj.apply_user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'eight'] and request.user == obj.apply_user else 'false', "flow_dict": flow_dict,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "请假申请")
        except:
            pass
        obj = LeaveRequest.objects.get(id=int(id))
        obj.current_audit_users.clear()
        obj.audit_users_already.add(request.user)
        leave_day = obj.days
        leave_type = obj.leave_type

        if obj.state == "one":
            audit_record = obj.leaverequestauditrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.leaverequestauditrecord_set.filter(node='two', state='unaudit'):
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                elif obj.leaverequestauditrecord_set.filter(node='three', state='unaudit'):
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "two":
            audit_record = obj.leaverequestauditrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                if obj.leaverequestauditrecord_set.filter(node='three', state='unaudit'):
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    next_audit_record = obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "three":
            audit_record = obj.leaverequestauditrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            audit_record = obj.leaverequestauditrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
                if leave_type in ["a", "j"]:
                    if request.user.leaverequesttypedays_set.filter(leave_type=leave_type, years=time.strftime("%Y", time.localtime())):
                        LeaveRequestTypeDays.objects.create(apply_user=request.user, leave_type=leave_type, days=leave_day, years=time.strftime("%Y", time.localtime()))
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        obj.state = obj_state
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "请假申请"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ContractCountersigningApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = BusinessContract.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.businesscontractauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.businesscontractauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "file_type": atta_obj.file_type,
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        flag = 'flase'
        for t in file_list:
            if t['file_type'] == '1':
                flag = 'true'

        if obj.product_company.id == 87:
            xuqiu_dep, xuqiu_id = [], []
            for tt in obj.requirement_department.all():
                xuqiu_dep.append(tt.name)
                xuqiu_id.append(str(tt.id))
        else:
            xuqiu_dep, xuqiu_id = [obj.product_company.name], [str(obj.product_company.id)]
        context = {'apply_user': obj.apply_user.real_name, 'create_time': obj.create_time.strftime('%Y-%m-%d %H:%M'), 'company': obj.company.name, 'Printing': obj.Printing,
                   'product_company': ", ".join(xuqiu_dep), 'contract_name': obj.contract_name, 'contract_number': obj.contract_number, 'documentation': obj.documentation,
                   'other_units': obj.other_units, 'contract_amount': obj.contract_amount, 'source': obj.source, 'content': obj.content, 'file_list': file_list, "audit_dic": audit_dic, "flag": flag,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine', 'ten', 'eleven'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine', 'ten', 'eleven'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict, "contract_effect": obj.contract_effect, "contract_off": obj.contract_off, "contract_type": obj.contract_type
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "合同会签")
        except:
            pass
        obj = BusinessContract.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        if obj.state != 'two':
            obj.current_audit_users.clear()

        if obj.state == 'one':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='one', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                if obj.businesscontractauditrecord_set.filter(node='two'):
                    next_audit_list = obj.businesscontractauditrecord_set.filter(node='two', state='unaudit')
                    obj_state = 'two'
                    for next_audit_obj in next_audit_list:
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                else:
                    next_audit_obj = obj.businesscontractauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='two', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                if obj.businesscontractauditrecord_set.filter(node='two', state='unaudit').count() == 1:
                    obj.current_audit_users.clear()
                    next_audit_obj = obj.businesscontractauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_obj.audit_people)
                else:
                    obj.current_audit_users.remove(request.user)
                    obj_state = 'two'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='three', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='four', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='five', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='six', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                if obj.businesscontractauditrecord_set.filter(node='nine', state='unaudit'):
                    next_audit_obj = obj.businesscontractauditrecord_set.filter(node='nine', state='unaudit').first()
                    obj_state = 'nine'
                else:
                    next_audit_obj = obj.businesscontractauditrecord_set.filter(node='eleven', state='unaudit').first()
                    obj_state = 'eleven'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'nine':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='nine', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='ten', state='unaudit').first()
                obj_state = 'ten'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'ten':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='ten', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='eleven', state='unaudit').first()
                obj_state = 'eleven'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'eleven':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='eleven', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                if not obj.businesscontractauditrecord_set.filter(node='ten'):
                    MakeCopy.objects.create(recipient=Staffing.objects.get(station='院长').post_personnel.all().first(),
                                            process_id=obj.id, type='f')
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "合同会签"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.contract_name[:15] + "……" if len(obj.contract_name) > 15 else obj.contract_name
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MedicalServiceApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = NewMedicalServices.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.newmedicalservicesauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        one_step = obj.newmedicalservicesauditrecord_set.filter(node__in=['one', 'two'])
        if one_step:
            apply_people = []
            apply = 'true'
            for obj_s in one_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['one'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        two_step = obj.newmedicalservicesauditrecord_set.filter(node='three')
        if two_step:
            apply_people = []
            apply = 'true'
            for obj_s in two_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['two'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        three_step = obj.newmedicalservicesauditrecord_set.filter(node='four')
        if three_step:
            apply_people = []
            apply = 'true'
            for obj_s in three_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['three'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        four_step = obj.newmedicalservicesauditrecord_set.filter(node='five')
        if four_step:
            apply_people = []
            apply = 'true'
            for obj_s in four_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['four'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
        type_dict = {"one": "综合医疗服务类", "two": "医技诊疗类", "three": "临床诊疗类"}
        category_dict = {"one": [{"category": "a", "value": "一般医疗服务"}, {"category": "b", "value": "一般检查治疗"}, {"category": "c", "value": "预防保健及其他"}, {"category": "d", "value": "其他医疗服务项目"}],
                         "two": [{"category": "e", "value": "医学影像"}, {"category": "f", "value": "超声检查"}, {"category": "g", "value": "核医学"}, {"category": "h", "value": "放射治疗"}, {"category": "i", "value": "检验"}, {"category": "j", "value": "血型与配血"}, {"category": "k", "value": "病理检查"}],
                         "three": [{"category": "l", "value": "经血管介入治疗"}, {"category": "m", "value": "临床各种系统诊疗"}, {"category": "n", "value": "手术治疗"}, {"category": "o", "value": "物理治疗与康复"}, {"category": "p", "value": "中医及民族医诊疗类"}]
                         }
        context = {'apply_user': obj.apply_user.real_name, 'company': obj.company.name, 'title': obj.title, 'number': obj.number, 'type': obj.type, 'type_dict': type_dict,
                   'reason': obj.reason, 'connotation': obj.connotation, 'note': obj.note, 'category': obj.category, 'file_list': file_list, "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'eight'] and request.user == obj.apply_user else 'false',
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number)[0].pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict, 'category_dict': category_dict}
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "新增医疗服务")
        except:
            pass
        obj = NewMedicalServices.objects.get(id=id)
        obj.audit_users_already.add(request.user)

        next_audit_obj, audit_obj = None, None
        if obj.state == 'one':
            audit_list = obj.newmedicalservicesauditrecord_set.filter(node__in=['one', 'two'], state='unaudit')
            for aud in audit_list:
                if aud.audit_people == request.user:
                    audit_obj = aud
            if state == 'audit':
                if obj.current_audit_users.count() == 1:
                    next_audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                else:
                    obj.current_audit_users.remove(request.user)
                    obj_state = 'one'
            else:
                obj_state = 'eight'

        elif obj.state == 'three':
            audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='three', state='unaudit',
                                                                     audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'eight'

        elif obj.state == 'four':
            audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='four', state='unaudit',
                                                                     audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                obj.current_audit_users.clear()
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.clear()
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.clear()
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.can_revise = '0'
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "临床管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SurgicalGradingApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = SurgicalGrading.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.surgicalgradingauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.surgicalgradingauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'apply_user': obj.apply_user.real_name, 'company': obj.company.name, 'gender': obj.gender, 'birthday_date': obj.birthday_date.split(" ")[0], 'education': obj.education,
                   'reason': obj.reason, 'professional_date': obj.professional_date.split(" ")[0], 'professional_title': obj.professional_title, 'current_surgical_level': obj.current_surgical_level,
                   'apply_surgical_level': obj.apply_surgical_level, 'file_list': file_list, "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'eight'] and request.user == obj.apply_user else 'false', "flow_dict": flow_dict,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "手术分级授权")
        except:
            pass
        obj = SurgicalGrading.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.surgicalgradingauditrecord_set.filter(node='one', state='unaudit',
                                                                  audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.surgicalgradingauditrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.surgicalgradingauditrecord_set.filter(node='two', state='unaudit',
                                                                  audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.surgicalgradingauditrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.surgicalgradingauditrecord_set.filter(node='three', state='unaudit',
                                                                  audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.can_revise = '0'
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "临床管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PhysicianPracticeApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', "")
        obj = SoloPracticeApply.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.solopracticeapplyauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.solopracticeapplyauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'apply_user': obj.apply_user.real_name, 'company': obj.company.name, 'university': obj.university, 'subject': obj.subject, 'doctor_qualified_number': obj.doctor_qualified_number,
                   'doctor_qualified_date': obj.doctor_qualified_date, 'doctor_ractice_number': obj.doctor_ractice_number, 'doctor_ractice_date': obj.doctor_ractice_date, 'birthday_date': obj.birthday_date.split(" ")[0],
                   "audit_dic": audit_dic, 'file_list': file_list,
                   "is_audit": "true" if obj.state in ['one', 'two'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'eight'] and request.user == obj.apply_user else 'false',
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number)[0].pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "临床医师单独执业资格")
        except:
            pass
        obj = SoloPracticeApply.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.solopracticeapplyauditrecord_set.filter(node='one', state='unaudit',
                                                                    audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.solopracticeapplyauditrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.solopracticeapplyauditrecord_set.filter(node='two', state='unaudit',
                                                                    audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'

        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.can_revise = '0'
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "临床管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = "临床医师单独执业资格申请"
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PartyGovernmentApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = PartyBuilding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.partybuildingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.partybuildingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        branch_list = ['中共京山市人民医院行管后勤一支部委员会', '中共京山市人民医院行管后勤二支部委员会', '中共京山市人民医院门诊医技支部委员会', '中共京山市人民医院内科系列一支部委员会', '中共京山市人民医院内科系列二支部委员会', '中共京山市人民医院外科系列一支部委员会', '中共京山市人民医院外科系列二支部委员会']
        context = {"apply_user": obj.apply_user.real_name, 'company': obj.company.name, 'TypeId':obj.TypeId, 'dep_type': obj.dep_type, 'branch_secretary': {'id': obj.branch_review.id, 'real_name': obj.branch_review.real_name} if obj.branch_review else {}, 'audit_dic': audit_dic, "file_list": file_list,
                   'total_amount': obj.total_amount, 'daxie': obj.daxie, "pay_detail": json.loads(obj.pay_detail),
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six"] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false', 'flow_dict': flow_dict,
                   "branch_review_obj": [{'id': i.id, "real_name": i.real_name} for i in Staffing.objects.get(station='支部书记').post_personnel.all()], "branch_list": branch_list,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "党建经费")
        except:
            pass
        obj = PartyBuilding.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.partybuildingrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.partybuildingrecord_set.filter(node='two'):
                    next_audit_record = obj.partybuildingrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                    obj.current_audit_users.add(next_audit_record.audit_people)

                else:
                    next_audit_record = obj.partybuildingrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.partybuildingrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.partybuildingrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.partybuildingrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.partybuildingrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.partybuildingrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.partybuildingrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.partybuildingrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.partybuildingrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.partybuildingrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "党建经费"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.application_reason[:15] + "……" if len(
            obj.application_reason) > 15 else obj.application_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ProjectSummitApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ObjectAudit.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.objectauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.objectauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'apply_user': obj.apply_user.real_name, 'company': obj.company.name, "w_time": obj.w_time, "r_time": obj.r_time, "work_name": obj.work_name, "describe": obj.describe,
                   "audit_ask": obj.audit_ask, "htje": obj.htje, "sgfzj": obj.sgfzj, "bmzj": obj.bmzj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_audit': 'true' if obj.state in ['one', 'two'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two'] and request.user == obj.apply_user else 'false', 'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "项目审计送审审批")
        except:
            pass
        obj = ObjectAudit.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.objectauditrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.objectauditrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'two':
            audit_record = obj.objectauditrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
                sjk_obj = Company.objects.get(id=22).head_people
                MakeCopy.objects.create(recipient=sjk_obj, process_id=obj.id, type='i')
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "审计送审"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.work_name[:15] + "……" if len(obj.work_name) > 15 else obj.work_name
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class PaymentApprovalApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = PaymentApproval.objects.get(id=id)
        if obj.topics_id:
            audit_dic = {}
            topics_obj = obj.topics_id
            for audit_obj in topics_obj.topicsauditrecord_set.all():
                node_display = ""
                if audit_obj.node == "B":
                    node_display = "分管领导"
                if audit_obj.node == "OPR":
                    node_display = "医院办公室初审"
                if topics_obj.type == 'xz':
                    if audit_obj.node == "YZ/SJ":
                        node_display = "院长意见"
                    if audit_obj.node == "YB/DB":
                        node_display = "医院办公室"
                else:
                    if audit_obj.node == "YB/DB":
                        if topics_obj.topicsauditrecord_set.filter(node="yb_result").count() or topics_obj.type == 'yb':
                            node_display = "医院办公室核稿"
                        else:
                            node_display = "党委办公室"
                    if audit_obj.node == "Y_D_leader":
                        node_display = "党委办公室分管领导"
                    if audit_obj.node == "YZ/SJ":
                        if topics_obj.type == 'db':
                            if topics_obj.is_yb:
                                node_display = "院长意见"
                            else:
                                node_display = "书记意见"
                        else:
                            node_display = "院长意见"
                if audit_obj.node == "yb_result":
                    node_display = "院长办公会会议结果"
                if audit_obj.node == "marks":
                    node_display = "议题备注"
                if audit_obj.node == "transfer":
                    node_display = "提交党委会"
                if audit_obj.node == "db_leader":
                    node_display = "分管领导"
                if audit_obj.node == "PG":
                    node_display = "党委办公室"
                if audit_obj.node == "db_one_step":
                    node_display = "分管领导"
                if audit_obj.node == "db_two_step":
                    node_display = "党委办公室"
                if audit_obj.node == "db_three_step":
                    node_display = "党委办公室分管领导"
                if audit_obj.node == "sj":
                    node_display = "书记意见"
                if audit_obj.node == "db_result":
                    node_display = "党委会会议结果"
                if audit_obj.node == "xz_result":
                    node_display = "行政例会会议结果"

                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': node_display,
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': node_display,
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]

            topic_audit_dic, topic_flow_dict = {}, {}
            for audit_obj in obj.paymentapprovalrecord_set.all():
                if audit_obj.node in topic_audit_dic:
                    topic_audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.paymentapprovalrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    topic_flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in topic_flow_dict]) + 1}
                    topic_audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
            help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
            data_dic = {
                "topic_type": "付款类" if topics_obj.topic_type == "1" else "经济合同类" if topics_obj.topic_type == "2" else "项目类" if topics_obj.topic_type == "3" else "文件类" if topics_obj.topic_type == "4" else "方案类" if topics_obj.topic_type == "5" else "其他事项",
                "pay_type": "合同付款" if topics_obj.pay_type == '1' else "固定资产/维修维保付款" if topics_obj.pay_type == '2' else "材料付款" if topics_obj.pay_type == '3' else "餐补付款" if topics_obj.pay_type == '4' else "学科经费" if topics_obj.pay_type == '5' else "科研经费" if topics_obj.pay_type == '6' else "一般付款",
                'apply_user': topics_obj.employee.real_name, "company": topics_obj.employee.company.name, 'state': topics_obj.get_state_display(), "whether_outweigh": "是" if topics_obj.whether_outweigh == "1" else "否",
                'yb_number': Topics.objects.get(id=int(topics_obj.HouseToParty_id)).number if topics_obj.HouseToParty_id else '',
                'main_file_list': main_file_list, 'number': topics_obj.number, 'topics_name': topics_obj.topics_name, "Payee": topics_obj.Payee, "receiving_account": topics_obj.receiving_account, "opening_bank": topics_obj.opening_bank,
                'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_text).decode()).decode()),
                'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_basis).decode()).decode()),
                'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.solution).decode()).decode()) if topics_obj.solution != "空" else "",
                'db_topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_text).decode()).decode()) if topics_obj.db_topics_text else "",
                'db_topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_basis).decode()).decode()) if topics_obj.db_topics_basis else "",
                'db_solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_solution).decode()).decode()) if topics_obj.db_solution else "",
                'topics_estimate': topics_obj.topics_estimate, 'help_department': help_department, 'help_department1': help_department1,
                'jfly': topics_obj.jfly if topics_obj.jfly else "", 'ysje': topics_obj.ysje if topics_obj.ysje else "", 'uuid': topics_obj.uuid,
                'audit_list': audit_dic, "topic_audit_dic": topic_audit_dic, "topic_flow_dict": topic_flow_dict, "topic_transfer": True,
                'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six"] and request.user in obj.current_audit_users.all() else 'false',
                'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false',
                'file_path': Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=topics_obj.uuid) else ''}
            returnDict = {'code': 200, 'message': 'success', 'data': data_dic}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.paymentapprovalrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.paymentapprovalrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                          "file_path": atta_obj.pdf_path.replace("\\", "/"),
                          "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                          "file_size": atta_obj.file_size,
                          "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                          "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                          "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

            context = {"apply_user": obj.apply_user.real_name, "company": obj.apply_user.company.name, "title": obj.title, "source": obj.source, "Payee": obj.Payee, "node": obj.node,
                       "receiving_account": obj.receiving_account, "total_money": obj.total_money, "daxie": obj.daxie, "opening_bank": obj.opening_bank, 'topic_audit_dic': audit_dic, "file_list": file_list,
                       "pay_type": "合同付款" if obj.pay_type == '1' else "固定资产/维修维保付款" if obj.pay_type == '2' else "材料付款" if obj.pay_type == '3' else "餐补付款" if obj.pay_type == '4' else "学科经费" if obj.pay_type == '5' else "科研经费" if obj.pay_type == '6' else "一般付款",
                       'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                       'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six"] and request.user in obj.current_audit_users.all() else 'false',
                       'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false',
                       'topic_flow_dict': flow_dict, "revise": revise, "topic_transfer": False,
                       'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                       }
            returnDict = {'code': 200, 'message': 'success', 'data': context}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "付款流程")
        except:
            pass
        obj = PaymentApproval.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.paymentapprovalrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.paymentapprovalrecord_set.filter(node='six', state='unaudit'):
                    next_audit_record = obj.paymentapprovalrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
                else:
                    if obj.paymentapprovalrecord_set.filter(node='two', state='unaudit'):
                        next_audit_record = obj.paymentapprovalrecord_set.filter(node='two', state='unaudit').first()
                        obj_state = 'two'
                    else:
                        next_audit_record = obj.paymentapprovalrecord_set.filter(node='three', state='unaudit').first()
                        obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.paymentapprovalrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                if obj.paymentapprovalrecord_set.filter(node='two', state='unaudit'):
                    next_audit_record = obj.paymentapprovalrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    next_audit_record = obj.paymentapprovalrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.paymentapprovalrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.paymentapprovalrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.paymentapprovalrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.paymentapprovalrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.paymentapprovalrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.paymentapprovalrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.paymentapprovalrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
                if obj.pay_type in ["5", "6"]:
                    try:
                        headers = {
                            "Content-Type": 'application/json'
                        }
                        for rson in json.loads(obj.pay_detail):
                            post_data = {
                                'key': 'hOJYdf7WoMTZV06Q',
                                'department_name': obj.apply_user.company.name,
                                'time': obj.create_time.strftime("%Y-%m-%d"),
                                'amount': re.findall("\d+.\d+", obj.topics_id.ysje)[0] if obj.topics_id else float(
                                    obj.total_money.replace(",", '')) / 10000,
                                'agent_name': obj.apply_user.real_name,
                                'reason': rson['goods_name']
                            }
                            req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                            print(req.text)
                    except:
                        print("同步更新出错")
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "付款流程"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ContractCountersignApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ContractApproval.objects.get(id=id)
        audit_dic = {}
        topics_obj = obj.topics_id
        for audit_obj in topics_obj.topicsauditrecord_set.all():
            node_display = ""
            if audit_obj.node == "B":
                node_display = "分管领导"
            if audit_obj.node == "OPR":
                node_display = "医院办公室初审"
            if topics_obj.type == 'xz':
                if audit_obj.node == "YZ/SJ":
                    node_display = "院长意见"
                if audit_obj.node == "YB/DB":
                    node_display = "医院办公室"
            else:
                if audit_obj.node == "YB/DB":
                    if topics_obj.topicsauditrecord_set.filter(node="yb_result").count() or topics_obj.type == 'yb':
                        node_display = "医院办公室核稿"
                    else:
                        node_display = "党委办公室"
                if audit_obj.node == "Y_D_leader":
                    node_display = "党委办公室分管领导"
                if audit_obj.node == "YZ/SJ":
                    if topics_obj.type == 'db':
                        if topics_obj.is_yb:
                            node_display = "院长意见"
                        else:
                            node_display = "书记意见"
                    else:
                        node_display = "院长意见"
            if audit_obj.node == "yb_result":
                node_display = "院长办公会会议结果"
            if audit_obj.node == "marks":
                node_display = "议题备注"
            if audit_obj.node == "transfer":
                node_display = "提交党委会"
            if audit_obj.node == "db_leader":
                node_display = "分管领导"
            if audit_obj.node == "PG":
                node_display = "党委办公室"
            if audit_obj.node == "db_one_step":
                node_display = "分管领导"
            if audit_obj.node == "db_two_step":
                node_display = "党委办公室"
            if audit_obj.node == "db_three_step":
                node_display = "党委办公室分管领导"
            if audit_obj.node == "sj":
                node_display = "书记意见"
            if audit_obj.node == "db_result":
                node_display = "党委会会议结果"
            if audit_obj.node == "xz_result":
                node_display = "行政例会会议结果"

            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': node_display, 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': node_display, 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        main_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"), "pdf_path": atta_obj.pdf_path, "file_type": "0",
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3], "id": atta_obj.id} for atta_obj in
            Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]

        file_flag = "false"
        for iiii in Topicsattachments.objects.filter(topics_number=obj.fj_number):
            file_flag = "true"
            main_file_list.append({"file_name": iiii.file_name if iiii.file_name else iiii.file_path.name.split('/')[-1], "file_path": iiii.pdf_path.replace("\\", "/"), "pdf_path": iiii.pdf_path, "file_type": "1",
                 "word_path": iiii.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": iiii.file_size, "uploader": iiii.uploader_user.real_name,
                 "upload_time": str(iiii.create_time).split(".")[0][:-3], "id": iiii.id})

        topic_audit_dic, topic_flow_dict = {}, {}
        for audit_obj in obj.contractapprovalrecord_set.all():
            if audit_obj.node in topic_audit_dic:
                topic_audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                                        'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                        'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.contractapprovalrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                topic_flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                                   'sear': len([i for i in topic_flow_dict]) + 1}
                topic_audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                     'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
        help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
        data_dic = {'apply_user': topics_obj.employee.real_name, "company": topics_obj.employee.company.name, 'state': obj.state, 'main_file_list': main_file_list, 'number': topics_obj.number, 'topics_name': topics_obj.topics_name,
                    "topic_type": "付款类" if topics_obj.topic_type == "1" else "经济合同类" if topics_obj.topic_type == "2" else "项目类" if topics_obj.topic_type == "3" else "文件类" if topics_obj.topic_type == "4" else "方案类" if topics_obj.topic_type == "5" else "其他事项",
                    "contract_type": "服务类" if topics_obj.contract_type == "1" else "货物类" if topics_obj.contract_type == "2" else "工程类" if topics_obj.contract_type == "3" else "其他类", "whether_outweigh": "是" if topics_obj.whether_outweigh == "1" else "否",
                    "Payee": topics_obj.Payee, "contract_name": topics_obj.contract_name, "contract_number": topics_obj.contract_number, 'yb_number': Topics.objects.get(id=int(topics_obj.HouseToParty_id)).number if topics_obj.HouseToParty_id else '',
                    'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_text).decode()).decode()),
                    'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_basis).decode()).decode()),
                    'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.solution).decode()).decode()) if topics_obj.solution != "空" else "",
                    'db_topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_text).decode()).decode()) if topics_obj.db_topics_text else "",
                    'db_topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_basis).decode()).decode()) if topics_obj.db_topics_basis else "",
                    'db_solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_solution).decode()).decode()) if topics_obj.db_solution else "",
                    'topics_estimate': topics_obj.topics_estimate, 'help_department': help_department,
                    'help_department1': help_department1, "file_flag": file_flag, 'jfly': topics_obj.jfly if topics_obj.jfly else "", 'ysje': topics_obj.ysje if topics_obj.ysje else "", 'uuid': topics_obj.uuid,
                    'audit_list': audit_dic, "topic_audit_dic": topic_audit_dic, "topic_flow_dict": topic_flow_dict,
                    'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false', "file_uuid": str(uuid.uuid4()),
                    'is_audit': 'true' if obj.state in ['negative', 'zero', 'one', 'two', 'three', 'four', 'five', "six"] and request.user in obj.current_audit_users.all() else 'false',
                    'is_stop': 'true' if obj.state in ['negative', 'zero', 'one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false',
                    'file_path': Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=topics_obj.uuid) else ''}
        returnDict = {'code': 200, 'message': 'success', 'data': data_dic}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "付款流程")
        except:
            pass
        obj = ContractApproval.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'negative':
            negative_uuid = request.POST.get('negative_uuid', '')
            contract_type_select = request.POST.get('contract_type_select', '')
            opposite_unit = request.POST.get('opposite_unit', '')
            contract_name = request.POST.get('contract_name', '')
            contract_number = request.POST.get('contract_number', '')
            audit_record = obj.contractapprovalrecord_set.filter(node='negative', state='unaudit').first()
            next_audit_record = obj.contractapprovalrecord_set.filter(node='zero', state='unaudit').first()
            obj_state = 'zero'
            state = "audit"
            obj.current_audit_users.add(next_audit_record.audit_people)
            obj.fj_number = negative_uuid
            obj.topics_id.contract_type = contract_type_select
            obj.topics_id.contract_name = contract_name
            obj.topics_id.contract_number = contract_number
            obj.topics_id.Payee = opposite_unit
            obj.topics_id.save()

        elif obj.state == 'zero':
            audit_record = obj.contractapprovalrecord_set.filter(node='zero', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='one', state='unaudit').first()
                obj_state = 'one'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'one':
            audit_record = obj.contractapprovalrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.contractapprovalrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.contractapprovalrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.contractapprovalrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.contractapprovalrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "付款流程"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MyReceiptApi(LoginRequiredMixin, View):
    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询标题
        datavalue = request.POST.get("datavalue", '')
        types = request.POST.get("types", "待收公文")

        if types == '已收公文':
            select_sql = f"""
                        SELECT types, SUM(num) FROM 
                        (SELECT b.type types, COUNT(b.type) num FROM (SELECT * FROM administrative_conferencememopeople WHERE state='accepted' AND audit_people_id={request.user.id}) a LEFT JOIN administrative_conferencememo b ON a.notice_id_id=b.id GROUP BY b.type	
                        UNION ALL
                        SELECT 'z' types, COUNT(*) num FROM administrative_officialdocumentspeople WHERE  state='accepted' AND audit_people_id={request.user.id}) base GROUP BY types ORDER BY types ASC
                    """
        else:
            select_sql = f"""
                                SELECT types, SUM(num) FROM 
                                (SELECT b.type types, COUNT(b.type) num FROM (SELECT * FROM administrative_conferencememopeople WHERE state='accept' AND audit_people_id={request.user.id}) a LEFT JOIN administrative_conferencememo b ON a.notice_id_id=b.id GROUP BY b.type	
                                UNION ALL
                                SELECT 'z' types, COUNT(*) num FROM administrative_officialdocumentspeople WHERE  state='accept' AND audit_people_id={request.user.id}) base GROUP BY types ORDER BY types ASC
                            """

        with connection.cursor() as cursor:
            cursor.execute(select_sql)
        all_data = cursor.fetchall()
        one_dict = {}
        for i in all_data:
            one_dict[i[0]] = str(i[1])

        if types == "已收公文":
            print(datavalue, search_data, page, page_size)
            totals_number, data_list = my_shouwen().my_yishou(datavalue, search_data, request, page, page_size)
        else:
            totals_number, data_list = my_shouwen().my_daishou(datavalue, search_data, request, page, page_size)
        returnDict = {'status': 'success', "totals": totals_number, "one_dict": one_dict, "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SystemSchedulingApi(LoginRequiredMixin, View):
    def post(self, request):
        now = datetime.now()
        # monday = now + timedelta(days=1)
        if 6 > now.weekday():
            day = 6 - now.weekday()
            sunday = now + timedelta(days=day)
        else:
            sunday = now
        if now.weekday() > 0:
            day = now.weekday()
            monday = now + timedelta(days=-day)
        else:
            monday = now
        two_line = [{'name': record.user.real_name, 'duty_date': record.date.strftime("%Y-%m-%d"),
                     'week': num_to_char(record.date.weekday() + 1)} for record in
                    SortLine.objects.filter(is_deleted=False, type='2', date__range=[monday, sunday])]
        one_line = [
            {'name': record.user.real_name, 'phone': record.user.mobile, 'type': record.get_day_type_display(),
             'duty_date': record.date.strftime("%Y-%m-%d"),
             'week': num_to_char(record.date.weekday() + 1)} for record in
            SortLine.objects.filter(is_deleted=False, type='1', date__range=[monday, sunday])]
        one_line_dict = {}
        for jj in one_line:
            if jj["duty_date"] in one_line_dict:
                one_line_dict[jj["duty_date"]].append(jj)
            else:
                one_line_dict[jj["duty_date"]] = [jj]

        two_line_dict = {}
        for tt in two_line:
            if tt["duty_date"] in two_line_dict:
                two_line_dict[tt["duty_date"]].append(tt)
            else:
                two_line_dict[tt["duty_date"]] = [tt]

        all_dict = {'one_line': one_line_dict, 'two_line': two_line_dict, 'today': time.strftime("%Y-%m-%d", time.localtime())}
        returnDict = {'code': 200, 'message': 'success', 'data': all_dict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class AttendanceInformationApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        all_dict = []
        obj_list = request.user.checkworkattendance_set.all()
        if obj_list.count():
            obj = obj_list.last()
            all_dict = [{"attendance_days": obj.attendance_days, "work_days": obj.work_days, "aid_jing": obj.aid_jing, "quarantine": obj.quarantine, "heterodyne": obj.heterodyne,
                         "education": obj.education, "planning": obj.planning, "maternity": obj.maternity, "annual": obj.annual, "absence": obj.absence, "sick": obj.sick,
                         "industrial": obj.industrial, "visit": obj.visit, "marriage": obj.marriage, "bereavement": obj.bereavement, "vacation": obj.vacation,
                         "parental_leave": obj.parental_leave, "notes": obj.notes, 'month': obj.attendance.work_month, 'year': obj.attendance.work_yesr}]

        returnDict = {'code': 200, 'message': 'success', 'data': all_dict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MySalaryApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        all_dict = []
        obj_list = request.user.salaryrecord_set.all()
        if obj_list.count():
            obj = obj_list.last()
            all_dict = [{"personnel_number": obj.personnel_number, "real_name": obj.real_name, "personnel_category": obj.personnel_category, "company": obj.company, "bank_account": obj.bank_account,
                         "post_wage": obj.post_wage, "salary_level_salary": obj.salary_level_salary, "standard_performance": obj.standard_performance, "protective_tape": obj.protective_tape, "car_tape": obj.car_tape, "health_allowance": obj.health_allowance,
                         "labor_insurance": obj.labor_insurance, "total_payable": obj.total_payable, "endowment_insurance": obj.endowment_insurance, "occupational_annuity": obj.occupational_annuity, "medical_insurance": obj.medical_insurance,
                         "unemployment_insurance": obj.unemployment_insurance, "housing_fund": obj.housing_fund, "deduction_insurance": obj.deduction_insurance, "deduction": obj.deduction, "hydropower": obj.hydropower, "other": obj.other,
                         "membership_fees": obj.membership_fees, "total_deduction": obj.total_deduction, "predict_amount": obj.predict_amount, "month": obj.month, "years": obj.years}]

        returnDict = {'code': 200, 'message': 'success', 'data': all_dict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MyPerformanceApi(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        all_dict = []
        obj_list = request.user.performancerecord_set.all()
        if obj_list.count():
            obj = obj_list
            all_dict = [{"department_number": obj.department_number, "department": obj.department, "post": obj.post, "category": obj.category, "job_id": obj.job_id, "names": obj.names,
                         "bank_number": obj.bank_number, "workload_performance": obj.workload_performance, "management_performance": obj.management_performance, "night_performance": obj.night_performance,
                         "consultation_performance": obj.consultation_performance, "expert_performance": obj.expert_performance, "medical_performance": obj.medical_performance, "individual_performance": obj.individual_performance,
                         "parking_performance": obj.parking_performance, "talent_performance": obj.talent_performance, "public_performance": obj.public_performance, "deduction": obj.deduction, "payable_performance": obj.payable_performance,
                         "personal_income_tax": obj.personal_income_tax, "actual_performance": obj.actual_performance, "deduction_remarks": obj.deduction_remarks, "month": obj.month, "years": obj.years}]

        returnDict = {'code': 200, 'message': 'success', 'data': all_dict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class AddressBookApi(LoginRequiredMixin, View):
    def post(self, request):
        stu_list = list(
            User.objects.filter(is_superuser=0, is_delete=0).values("real_name", "head_portrait", "job_number"))
        all_dict = {}
        for i in stu_list:
            initial = hanzi_to_pinyin(i["real_name"])
            head_portrait1 = "/media/" + str(i["head_portrait"])
            if head_portrait1 == "/media/" or not os.path.exists(os.getcwd().replace('\\', '/') + head_portrait1):
                head_portrait1 = "/static/personal_center/img/头像.png"
            if "曾" == i["real_name"][0]:
                initial = "Z"
            if initial in all_dict:
                all_dict[initial].append(
                    {"name": i["real_name"], "picture": head_portrait1, "job_number": i["job_number"]})
            else:
                all_dict[initial] = [{"name": i["real_name"], "picture": head_portrait1, "job_number": i["job_number"]}]
        friend_list = {}
        for i in sorted(all_dict):
            friend_list[i] = all_dict[i]
        returnDict = {'code': 200, 'message': 'success', 'data': friend_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ExternalCorrespondenceDetailViewApi(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = Correspondence.objects.get(id=int(id))

        p_obj = obj.correspondencepeople_set.filter(audit_people=request.user, state='accept')
        if p_obj.count():
            p_obj.first().state = 'accepted'
            p_obj.first().update_time = datetime.now()
            p_obj.first().save()

        if int(id) <= 4:
            if obj.correspondencepeople_set.filter(state='accept').count() == 0 and obj.type == 'four':
                obj.type = 'five'
                obj.save()

            approve_flag = ""
            if request.user in obj.current_audit_users.all():
                approve_flag = True
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", '/'),
                 "pdf_path": atta_obj.pdf_path.replace("\\", '/'),
                 "file_size": atta_obj.file_size,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 'word_path': os.getcwd() + "/media/" + str(atta_obj.file_path).replace("\\", '/'),
                 "uploader": atta_obj.uploader_user.real_name, "id": atta_obj.id,
                 "topics_number": atta_obj.topics_number} for atta_obj in
                Topicsattachments.objects.filter(topics_number=obj.uuid, file_type="0")]

            file_list1 = [
                {"file_name": atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", '/')}
                for atta_obj in
                Topicsattachments.objects.filter(topics_number=obj.uuid, file_type="1")]

            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.correspondencerecord_set.filter(~Q(node='eight')):
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append(
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state,
                         'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                         'audit_note': audit_obj.audit_note,
                         'audit_time': audit_obj.update_time.strftime(
                             "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                     audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [
                        {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                         'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                         'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime(
                            "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                         'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (
                                     audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            appave_count = obj.correspondencerecord_set.filter(~Q(node='eight')).values(
                "audit_people").distinct().count()

            recive_people, no_recive, recive = [], [], []
            for record in obj.correspondencepeople_set.all():
                one_dict = {'user': record.audit_people.real_name, 'state': record.get_state_display(),
                            'signature_picture': '/media/' + str(record.audit_people.signature_picture) if (
                                        record.audit_people.signature_picture and record.state == 'accepted') else '',
                            'update_time': record.update_time.strftime(
                                "%Y-%m-%d %H:%M") if record.state == 'accepted' else ''}
                recive_people.append(one_dict)
                if record.state == 'accept':
                    no_recive.append(one_dict)
                else:
                    recive.append(one_dict)

            staff_obj = Staffing.objects.filter(station="办公室")

            flag = 0
            if staff_obj:
                for tt in staff_obj:
                    personnel = tt.post_personnel.all()
                    for jj in personnel:
                        if jj == request.user:
                            flag = 1

            data_dic = {
                'id': obj.id, 'appave_count': appave_count, 'yes_count': len(recive), 'recive': recive, 'node': obj.get_type_display(), 'no_count': len(no_recive), 'no_recive': no_recive,
                'type': obj.type, 'all_count': len(recive_people), 'recive_people': recive_people, 'apply_user': obj.apply_user.real_name, 'department': obj.apply_user.department, 'send_number': obj.send_number,
                'recive_number': obj.recive_number, 'title': obj.title, "uuid": obj.uuid, 'send_company': obj.send_company, 'content': obj.content, 'annotated_text': obj.annotated_text, 'time_limit': obj.time_limit, 'remarks': obj.remarks, 'file_list': file_list,
                'flag': flag, 'fenfa_flag': 'true' if obj.type == 'eight' and request.user == obj.apply_user else 'flase', 'file_list1': file_list1, 'recive_time': obj.recive_time.strftime("%Y-%m-%d %H:%M"), 'revocation_flag': 'true',
                'file_path': Topicsattachments.objects.filter(topics_number=obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.uuid) else "",
                'is_stop': 'true' if obj.type in ['one', 'two', 'three', 'four', 'six', 'seven', 'eight'] and request.user == obj.apply_user else 'false',
            }
            returnDict = {'data_dic': data_dic, "audit_dic": audit_dic, "approve_flag": approve_flag}
            return render(request, "personal_center/ExternalCorrespondenceDetail.html", returnDict)
        else:
            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.correspondencerecord_set.filter(~Q(node='eight')):
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                      'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.correspondencerecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                                  'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"), "file_type": atta_obj.file_type,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.uuid)]

            ReceivingObj = obj.correspondencepeople_set.all()
            ReceivingList = []
            for receiving in ReceivingObj:
                ReceivingList.append({"receiving": receiving.audit_people.real_name, "time": receiving.update_time.strftime("%Y-%m-%d %H:%M"), "state": receiving.state,
                                      "signature_picture": '/media/' + str(receiving.audit_people.signature_picture) if receiving.audit_people.signature_picture else ''})
            withdrawal = "false"
            received_obj = obj.correspondencerecord_set.filter(audit_people=request.user, state="audit")
            if received_obj.count():
                if received_obj.last().node == "one" and obj.state == "two":
                    withdrawal = "true"
                elif received_obj.last().node == "two" and obj.state == "three":
                    withdrawal = "true"
                elif received_obj.last().node == "three" and (obj.state == "three" or obj.state == "four"):
                    withdrawal = "true"
                elif received_obj.last().node == "four" and obj.state == "five":
                    withdrawal = "true"
                else:
                    withdrawal = "false"

            context = {"id": obj.id, "state": obj.state, "apply_user": obj.apply_user.real_name, "department": obj.apply_user.company.name, 'audit_dic': audit_dic, "file_list": file_list, "withdrawal": withdrawal,
                       "send_number": obj.send_number, "recive_number": obj.recive_number, "send_company": obj.send_company, "title": obj.title, 'uuid': obj.uuid,
                       "content": obj.content, "annotated_text": obj.annotated_text, "time_limit": obj.time_limit, "remarks": obj.remarks,
                       'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) else 'false',
                       'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                       'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user == obj.apply_user else 'false',
                       'flow_dict': flow_dict, "recive_time": obj.recive_time.strftime("%Y-%m-%d %H:%M"),
                       "leader_obj": [{"id": i.id, "real_name": i.real_name} for i in User.objects.filter(group_id__in=[1, 2])], "recive_people": ReceivingList,
                       'file_path': Topicsattachments.objects.filter(topics_number=obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.uuid) else ""
                       }
            returnDict = {'code': 200, 'message': 'success', 'data': context}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ExternalCorrespondenceApproveViewApi(LoginRequiredMixin, View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        opinion_detail = request.POST.get("audit_note", '')
        approve = request.POST.get("state", '')

        obj = Correspondence.objects.get(id=int(flow_id))
        print("====================", obj.state,
              obj.correspondencerecord_set.filter(node='two', state='unaudit').count())
        obj.audit_users_already.add(request.user)
        if obj.state == "one":
            obj.current_audit_users.clear()
            audit_record = obj.correspondencerecord_set.filter(node='one', state='unaudit').first()
            if approve == "audit":
                leader_prople = request.POST.get("leader_prople", '')
                AuditPeople = User.objects.get(id=int(leader_prople))
                CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit",
                                                    audit_people=AuditPeople, node="two")
                obj.current_audit_users.add(AuditPeople)
                obj.leaders = AuditPeople
                obj.state = "two"
            else:
                obj.state = "eight"
                obj.type = "f"
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "two":
            obj.current_audit_users.clear()
            audit_record = obj.correspondencerecord_set.filter(node='two', state='unaudit').first()
            if approve == "audit":
                Distributors = request.POST.get("Distributors", '')
                distributors_list = re.findall('\((.*?)\)', Distributors)
                ReadingPersonnel = request.POST.get("ReadingPersonnel", '')
                for i in distributors_list:
                    AuditPeople = User.objects.get(job_number=i)
                    CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit",
                                                        audit_people=AuditPeople, node="three")
                    obj.current_audit_users.add(AuditPeople)
                CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit",
                                                    audit_people=obj.leaders, node="four")
                CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit",
                                                    audit_people=Company.objects.get(id=80).head_people, node="five")
                obj.state = "three"

                items = []
                receive_people = re.findall('\((.*?)\)', ReadingPersonnel)
                receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
                for receive_people_obj in receive_people_objs:
                    off_obj = CorrespondencePeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
                    items.append(off_obj)
                CorrespondencePeople.objects.bulk_create(items)

            else:
                obj.state = "eight"
                obj.type = "f"
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "three":
            audit_record = obj.correspondencerecord_set.get(node='three', state='unaudit', audit_people=request.user)
            if approve == "audit":
                obj.current_audit_users.remove(request.user)
                audit_record.state = approve
                audit_record.save()
                Receipt = request.POST.get("Receipt", '')
                audit_record.img_path = Receipt
                if obj.correspondencerecord_set.filter(node='three', state='unaudit').count():
                    obj.state = "three"
                else:
                    obj.type = "a"
                    obj.state = "four"
                    obj.current_audit_users.add(obj.leaders)
            else:
                obj.current_audit_users.clear()
                obj.state = "eight"
                obj.type = "f"
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == "four":
            obj.current_audit_users.clear()
            audit_record = obj.correspondencerecord_set.get(node='four', state='unaudit', audit_people=request.user)
            if approve == "audit":
                obj.state = "five"
                obj.current_audit_users.add(Company.objects.get(id=80).head_people)
            else:
                obj.state = "three"
                obj.type = "f"
                set_list = []
                three_step = obj.correspondencerecord_set.filter(node='three')
                for step in three_step:
                    if step.audit_people not in set_list:
                        CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit",
                                                            audit_people=step.audit_people, node="three")
                        obj.current_audit_users.add(step.audit_people)
                CorrespondenceRecord.objects.create(official_documents_id=obj, state="unaudit",
                                                    audit_people=obj.leaders, node="four")

        else:
            obj.current_audit_users.clear()
            audit_record = obj.correspondencerecord_set.get(node='five', state='unaudit', audit_people=request.user)
            if approve == "audit":
                obj.state = "six"
                obj.type = "e"
            else:
                obj.state = "eight"
                obj.current_audit_users.add(obj.apply_user)

        audit_record.update_time = datetime.now()
        audit_record.state = approve
        audit_record.audit_note = opinion_detail
        audit_record.save()
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "外部来函"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ExternalCorrespondenceReceive(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        receive_people = request.POST.get('receive_people', None)
        message = request.POST.get('message', None)
        obj = Correspondence.objects.get(id=int(id))
        items = []
        receive_people = re.findall('\((.*?)\)', receive_people)
        receive_people_objs = User.objects.filter(job_number__in=receive_people, is_delete="0")
        mobile_list = []
        for receive_people_obj in receive_people_objs:
            mobile_list.append(receive_people_obj.mobile)
            off_obj = CorrespondencePeople(notice_id=obj, state='accept', audit_people=receive_people_obj)
            items.append(off_obj)
        obj.current_audit_users.clear()
        CorrespondencePeople.objects.bulk_create(items)
        if receive_people:
            obj.type = 'four'
        else:
            obj.type = 'five'
        obj.save()
        if str(message) == '1':
            message_str = f'外部来函：您有一份“{obj.recive_number}”“{obj.title}”的外部来函需要处理接收，请您在OA系统上查收。'
            send_mssage(mobile_list, message_str)
        returnDict = {'code': 200, 'message': '操作成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ServiceProcurementApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = PurchasingRequisition.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.purchasingrequisitionrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.purchasingrequisitionrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': request.user.real_name, 'position': request.user.post, 'mobile': obj.apply_user.mobile, 'company': obj.company.name, 'AmountWords': obj.AmountWords,
                   'department': request.user.company.name, 'apply_user': obj.apply_user.real_name, "audit_dic": audit_dic, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
                   'ApplicationReason': obj.ApplicationReason, 'ApplicationType': obj.ApplicationType, 'ServiceContent': obj.ServiceContent, 'BudgetAmount': obj.BudgetAmount,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['six'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'six'] and request.user == obj.apply_user else 'false',
                   'revise': revise, "flow_dict": flow_dict
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ServiceProcurementApprovalApi(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "服务采购")
        except:
            pass
        obj = PurchasingRequisition.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.purchasingrequisitionrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.purchasingrequisitionrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'six'
        elif obj.state == 'two':
            audit_obj = obj.purchasingrequisitionrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.purchasingrequisitionrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'six'
        elif obj.state == 'three':
            audit_obj = obj.purchasingrequisitionrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.purchasingrequisitionrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'six'
        elif obj.state == 'four':
            audit_obj = obj.purchasingrequisitionrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                three_appave = Company.objects.get(id=27).head_people
                MakeCopy.objects.create(recipient=three_appave, process_id=obj.id, type='d')
            else:
                obj_state = 'six'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'six':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "服务采购"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.ApplicationReason[:15] + "……" if len(obj.ApplicationReason) > 15 else obj.ApplicationReason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ProcurementGoodsViewApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = GoodsProcure.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.goodsprocurerecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.goodsprocurerecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': request.user.real_name, 'position': request.user.post, 'mobile': obj.apply_user.mobile, 'company': obj.company.name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
                   'department': request.user.company.name, 'apply_user': obj.apply_user.real_name, "audit_dic": audit_dic, 'PurchaseReason': obj.PurchaseReason, 'ApplicationType': obj.ApplicationType,
                   'GoodsName': obj.GoodsName, 'GoodsNumber': obj.GoodsNumber, 'MaterialQuality': obj.MaterialQuality, 'OtherRequirements': obj.OtherRequirements, 'custom_made_value': obj.custom_made_value,
                   'BudgetAmount': obj.BudgetAmount, 'AmountWords': obj.AmountWords,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['six'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'six'] and request.user == obj.apply_user else 'false',
                   'revise': revise, "flow_dict": flow_dict
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GoodsProcurementApprovalApi(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "货物采购")
        except:
            pass
        obj = GoodsProcure.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.goodsprocurerecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.goodsprocurerecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'six'
        elif obj.state == 'two':
            audit_obj = obj.goodsprocurerecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.goodsprocurerecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'six'
        elif obj.state == 'three':
            audit_obj = obj.goodsprocurerecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.goodsprocurerecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'six'
        elif obj.state == 'four':
            audit_obj = obj.goodsprocurerecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                three_appave = Company.objects.get(id=27).head_people
                MakeCopy.objects.create(recipient=three_appave, process_id=obj.id, type='e')
            else:
                obj_state = 'six'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'six':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "货物采购"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.PurchaseReason[:15] + "……" if len(obj.PurchaseReason) > 15 else obj.PurchaseReason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MaintenanceRenovationViewApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = MaintenanceRenovation.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.maintenancerenovationrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.maintenancerenovationrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': request.user.real_name, 'position': request.user.post, 'mobile': obj.apply_user.mobile, 'company': obj.company.name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
                   'department': request.user.company.name, 'apply_user': obj.apply_user.real_name, "audit_dic": audit_dic, 'EntryName': obj.EntryName, 'CostEstimating': obj.CostEstimating,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false', 'file_list': file_list,
                   "is_edit": "true" if (obj.state in ['six'] and request.user == obj.apply_user) or revise else 'false', 'ApplicationReason': obj.ApplicationReason,
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'six'] and request.user == obj.apply_user else 'false', 'DurationRequirements': obj.DurationRequirements,
                   'revise': revise, "flow_dict": flow_dict
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MaintenanceRenovationApprovalApi(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "维修改造")
        except:
            pass
        obj = MaintenanceRenovation.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.remove(request.user)
        next_audit_obj = None
        if obj.state == 'one':
            EntryName = request.POST.get('EntryName', '')
            CostEstimating = request.POST.get('CostEstimating', '')
            BudgetDetails = request.POST.get('BudgetDetails', '')
            DurationRequirements = request.POST.get('DurationRequirements', '')
            obj.EntryName = EntryName
            obj.CostEstimating = CostEstimating
            obj.DurationRequirements = DurationRequirements
            obj.BudgetDetails = BudgetDetails

            audit_obj = obj.maintenancerenovationrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.maintenancerenovationrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'six'
        elif obj.state == 'two':
            audit_obj = obj.maintenancerenovationrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.maintenancerenovationrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'six'
        elif obj.state == 'three':
            audit_obj = obj.maintenancerenovationrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.maintenancerenovationrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'six'
        elif obj.state == 'four':
            audit_obj = obj.maintenancerenovationrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                three_appave = Company.objects.get(id=27).head_people
                MakeCopy.objects.create(recipient=three_appave, process_id=obj.id, type='g')
            else:
                obj_state = 'six'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'six':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "维修改造"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.ApplicationReason[:15] + "……" if len(obj.ApplicationReason) > 15 else obj.ApplicationReason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PurchaseViewApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ComputerDevice.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.computerdevicerecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.computerdevicerecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': request.user.real_name, 'position': request.user.post, 'apply_user': obj.apply_user.real_name, 'mobile': obj.apply_user.mobile, 'company': obj.company.name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
                   'department': request.user.company.name, "audit_dic": audit_dic, 'ApplicationReason': obj.ApplicationReason,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['six'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'six'] and request.user == obj.apply_user else 'false',
                   'revise': revise, "flow_dict": flow_dict, "ApplicationDetail": json.loads(obj.ApplicationDetail)
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PurchaseApprovalApi(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "计算机及相关设备购置")
        except:
            pass
        obj = ComputerDevice.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.computerdevicerecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.computerdevicerecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'six'
        elif obj.state == 'two':
            audit_obj = obj.computerdevicerecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.computerdevicerecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'six'
        elif obj.state == 'three':
            audit_obj = obj.computerdevicerecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.computerdevicerecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'six'
        elif obj.state == 'four':
            audit_obj = obj.computerdevicerecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                three_appave = Company.objects.get(id=31).head_people
                MakeCopy.objects.create(recipient=three_appave, process_id=obj.id, type='h')
            else:
                obj_state = 'six'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'six':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "后勤管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = "计算机及相关设备购置"
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 查询聊天记录
class QueryRecordsApi(LoginRequiredMixin, View):
    def post(self, request):
        from_people = request.POST.get('from_people', None)  # 发信人
        roomName = request.POST.get('roomName', None)  # 收信人

        try:
            data_list = []
            chat_obj = chatting_records.objects.filter(Q(from_user=User.objects.get(job_number=from_people), to_user=User.objects.get(job_number=roomName)) |
                                                       Q(from_user=User.objects.get(job_number=roomName), to_user=User.objects.get(job_number=from_people))
                                                       ).order_by("create_time")

            for i in chat_obj:
                one_dict = json.loads(i.content)
                data_list.append(one_dict[0])
        except:
            data_list = []
        returnDict = {"code": 200, "message": "success", "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class BiddingProjectApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = BiddingProcurementProject.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.biddingprocurementprojectrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.biddingprocurementprojectrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [
                    {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                     'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                     'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                     'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {"apply_user": obj.apply_user.real_name, 'mobile': obj.apply_user.mobile, 'company': obj.company.name, 'create_time': obj.create_time.strftime("%Y-%m-%d"),
                   "ApplicationReason": obj.ApplicationReason, 'categories': obj.get_categories(), 'budget_amount': obj.budget_amount, 'source': '单位资金' if obj.source == '1' else '财政拨款',
                   'project_leader': obj.project_leader, 'telephone': obj.telephone, 'contact_person': obj.contact_person, 'contact_telephone': obj.contact_telephone, 'project_meeting': obj.get_meeting(),
                   'minutes_number_year': obj.minutes_number_year, 'minutes_number_number': obj.minutes_number_number, 'topic_number': obj.topic_number, 'procurement': '是' if obj.open_ornot == "1" else '否',
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false', 'audit_dic': audit_dic, "file_list": file_list,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false', 'state': obj.state,
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false', 'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class BiddingProjectApprovalApi(LoginRequiredMixin, View):
    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        procurement = request.POST.get("procurement", None)
        approval_leader = request.POST.get("approval_leader", None)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "招标采购项目")
        except:
            pass
        obj = BiddingProcurementProject.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.open_ornot = procurement
            else:
                obj_state = 'eight'
        elif obj.state == 'four':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.biddingprocurementprojectrecord_set.filter(node='five'):
                    next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                else:
                    obj_state = 'seven'
            else:
                obj_state = 'eight'
        elif obj.state == 'five':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.amount_conditions == '1':
                    obj_state = 'seven'
                    approval_department = obj.company.head_people
                    MakeCopy.objects.create(recipient=approval_department, process_id=obj.id, type='j')
                    zbb_obj = Company.objects.get(id=9)
                    zbb_appave = zbb_obj.head_people
                    MakeCopy.objects.create(recipient=zbb_appave, process_id=obj.id, type='j')
                    MakeCopy.objects.create(recipient=zbb_obj.leaders_id, process_id=obj.id, type='j')
                    MakeCopy.objects.create(recipient=obj.company.leaders_id, process_id=obj.id, type='j')
                else:
                    next_audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
            else:
                obj_state = 'eight'
        elif obj.state == 'six':
            audit_obj = obj.biddingprocurementprojectrecord_set.filter(node='six', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "招标采购"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.ApplicationReason[:15] + "……" if len(obj.ApplicationReason) > 15 else obj.ApplicationReason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MedicalEthicsDetailViewApi(LoginRequiredMixin, View):
    def get(self, request):
        id = request.GET.get('id', None)
        department = request.user.company.name
        obj = EvaluationOfMedicalEthics.objects.get(id=int(id))

        audit_list = []
        for audit_obj in obj.evaluationopinion_set.all():
            audit_list.append(
                {'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state == 'audit' else '',
                 'signature_picture': '/media/' + str(
                     audit_obj.audit_people.signature_picture) if audit_obj.state == 'audit' else '',
                 'node': audit_obj.node, "state": audit_obj.state,
                 'audit_note': audit_obj.audit_note, 'audit_people': audit_obj.audit_people.real_name
                 }
            )

        context = {
            "apply_user": obj.apply_user.real_name, "title": f"{datetime.now().year - 1}年度医德考评登记表", "total_score": obj.total_score, "seal_path": "/static/personal_center/测试专用章/医德医风.png",
            "gender": "男" if obj.gender == 'male' else "女", "birthday_date": obj.birthday_date, "political_status": obj.political_status, "education": obj.education,
            "professional_title": obj.professional_title, "employ_date": obj.employ_date, "job": obj.job, "apply_company": obj.apply_company.name, "content": obj.content,
            "item_list": json.loads(obj.item_list) if obj.item_list else "", "audit_list": audit_list, "level": obj.get_level_display(),
            "one_appove_time": obj.evaluationopinion_set.filter(node="one").last().update_time.strftime("%Y-%m-%d") if obj.evaluationopinion_set.filter(node="one", state='audit').count() else "",
            "two_appove_time": obj.evaluationopinion_set.filter(node="two").last().update_time.strftime("%Y-%m-%d"),
            "two_appove_audit": obj.evaluationopinion_set.filter(node="two").last().audit_note, "status": obj.get_state_str(),
            "three_appove_time": obj.evaluationopinion_set.filter(node="three").last().update_time.strftime("%Y-%m-%d") if obj.state in ["five"] else "",
            "three_appove_audit": obj.evaluationopinion_set.filter(node="three").last().audit_note if obj.state in ["five"] else "",
            "is_audit": "true" if (obj.evaluationopinion_set.filter(node="one").first().audit_people == request.user and obj.state == "one") else "false"
        }
        returnDict = {'code': 200, 'message': 'success', 'data': context}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

    def post(self, request):
        present_id = request.POST.get('id', None)
        obj = EvaluationOfMedicalEthics.objects.get(id=int(present_id))
        obj.audit_users_already.add(request.user)
        item_list = request.POST.get('item_list', None)  # [{'id': 1, 'score': 10}]
        total_score = request.POST.get('total_score', None)
        try:
            RecordAndPush().OperationRecords(request, "医德医风")
        except:
            pass
        if float(total_score) >= 90 and float(total_score) <= 100:
            obj.level = 'best'
        elif float(total_score) >= 80 and float(total_score) < 90:
            obj.level = 'good'
        elif float(total_score) >= 70 and float(total_score) < 80:
            obj.level = 'ordinary'
        else:
            obj.level = 'bad'
        obj.total_score = total_score
        obj.item_list = item_list

        opinion = obj.evaluationopinion_set.filter(node='one', audit_people=request.user).first()
        opinion.update_time = datetime.now()
        opinion.state = 'audit'
        opinion.save()
        obj.current_audit_users.clear()
        obj.save()
        returnDict = {'code': 200, 'message': '审批成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MedicalEthicsOverviewViewApi(LoginRequiredMixin, View):
    def post(self, request):
        today = datetime.today()
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", '')  # 查询关键词
        LevalType = request.POST.get("LevalType", '')
        year = request.POST.get('search_year', today.year - 1)  # 年份查询
        dept = request.POST.get('search_dept', '')  # 查询部门

        if dept:
            objs = EvaluationOfMedicalEthics.objects.filter(
                Q(apply_user__real_name__contains=search_data) | Q(title__contains=search_data) | Q(
                    education__contains=search_data) |
                Q(employ_date__contains=search_data) | Q(birthday_date__contains=search_data) | Q(
                    job__contains=search_data) | Q(political_status__contains=search_data) |
                Q(apply_company__name__contains=search_data) | Q(professional_title__contains=search_data),
                state__in=['three', 'five'], year=year, level__contains=LevalType,
                apply_company__id=dept).order_by('create_time')
        else:
            objs = EvaluationOfMedicalEthics.objects.filter(
                Q(apply_user__real_name__contains=search_data) | Q(title__contains=search_data) | Q(
                    education__contains=search_data) |
                Q(employ_date__contains=search_data) | Q(birthday_date__contains=search_data) | Q(
                    job__contains=search_data) | Q(political_status__contains=search_data) |
                Q(apply_company__name__contains=search_data) | Q(professional_title__contains=search_data),
                state__in=['three', 'five'], year=year, level__contains=LevalType).order_by('create_time')

        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            data_list.append(
                {'id': obj.id, 'apply_user': obj.apply_user.real_name,
                 'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"), "company": obj.apply_company.name,
                 "professional_title": obj.professional_title, "employ_date": obj.employ_date,
                 "job": obj.job, 'level': obj.get_level_display(), 'state': obj.get_state_str(),
                 'url': '<a class="plugin-action" id="' + str(obj.id) + '" href="' + str(obj.id) + '">查看</a>'
                 })
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class MedicalEthicsPublicityViewApi(LoginRequiredMixin, View):
    def post(self, request):
        today = datetime.today()
        years = request.POST.get('years', today.year - 1)
        CompanyObj = EvaluationOfMedicalEthics.objects.filter(state__in=['three', 'five'], year=years).values("apply_company").distinct()
        # ===========================================================构建表格数据===========================================================
        examine_data_list, serial = [], 1
        for dept in CompanyObj:
            com_obj = Company.objects.get(id=int(dept["apply_company"]))
            examine_obj = EvaluationOfMedicalEthics.objects.filter(state__in=['three', 'five'], year=years,
                                                                   apply_company=com_obj).order_by('create_time')
            # 优秀数据获取
            best_obj = examine_obj.filter(level='best')
            best_prople = ','.join([i.apply_user.real_name for i in best_obj])
            # =================================================================良好数据获取=================================================================
            good_obj = examine_obj.filter(level='good')
            good_prople = ','.join([i.apply_user.real_name for i in good_obj])
            # =================================================================一般数据获取=================================================================
            ordinary_obj = examine_obj.filter(level='ordinary')
            ordinary_prople = ','.join([i.apply_user.real_name for i in ordinary_obj])
            # =================================================================较差数据获取=================================================================
            bad_obj = examine_obj.filter(level='bad')
            bad_prople = ','.join([i.apply_user.real_name for i in bad_obj])
            examine_data_list.append(
                {"company_name": com_obj.name, "participate_number": examine_obj.count(), "best_prople": best_prople,
                 "best_count": best_obj.count(),
                 "good_prople": good_prople, "ordinary_prople": ordinary_prople, "bad_prople": bad_prople,
                 "serial": serial})
            serial += 1
        returnDict = {'code': 200, 'message': 'success!', "data": examine_data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DepartmentReviewSubmission(LoginRequiredMixin, View):
    def post(self, request):
        pass

class DepartmentSummary(LoginRequiredMixin, View):
    def post(self, request):
        today = datetime.today()
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", "")  # 查询标题
        search_year = request.POST.get("search_year", today.year - 1)

        objs = EvaluationOpinion.objects.filter(
            Q(parent_id__apply_user__real_name__contains=search_data) | Q(parent_id__title__contains=search_data) | Q(parent_id__education__contains=search_data) |
            Q(parent_id__employ_date__contains=search_data) | Q(parent_id__birthday_date__contains=search_data) | Q(parent_id__job__contains=search_data) | Q(parent_id__political_status__contains=search_data) |
            Q(parent_id__apply_company__name__contains=search_data) | Q(parent_id__professional_title__contains=search_data), audit_people=request.user, node='one',
            parent_id__year=search_year).order_by('create_time')
        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            if obj.parent_id.state == 'one':
                if obj.state == "unaudit":
                    url_text = "审核"
                else:
                    url_text = "修改"
            else:
                url_text = "查看"
            data_list.append(
                {'id': obj.parent_id.id, 'apply_user': obj.parent_id.apply_user.real_name,
                 'create_time': obj.parent_id.create_time.strftime("%Y-%m-%d %H:%M"), "title": obj.parent_id.title,
                 "professional_title": obj.parent_id.professional_title, "employ_date": obj.parent_id.employ_date,
                 "job": obj.parent_id.job,
                 'level': obj.parent_id.get_level_display(), 'state': obj.parent_id.get_state_str(),
                 })
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class FallLevelView(LoginRequiredMixin, View):
    def post(self, request):
        flow_id = request.POST.get("flow_id", '')           # 流程ID
        leval_select = request.POST.get("leval_select", '')           # 级别
        fall_opinion = request.POST.get("fall_opinion", '')           # 意见

        obj = EvaluationOfMedicalEthics.objects.get(id=int(flow_id))
        obj.level = leval_select
        obj.state = "five"
        obj.save()

        EvaluationOpinion.objects.create(parent_id=obj, audit_people=request.user, node='three', audit_note=fall_opinion, state="audit")

        returnDict = {'code': 200, 'message': '操作成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BatchApproval(LoginRequiredMixin, View):
    def post(self, request):
        id_list = request.POST.get("id_list", [])
        if id_list:
            for i in json.loads(id_list):
                obj = EvaluationOfMedicalEthics.objects.get(id=int(i))
                obj.state = 'five'
                obj.save()

                EvaluationOpinion.objects.create(parent_id=obj, audit_people=request.user, node='three', audit_note="经过小组讨论，同意考核结果。", state="audit")
            returnDict = {'code': 200, 'message': '操作成功!'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'code': 400, 'message': '请选择审批流程!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class GetJsCode(LoginRequiredMixin, View):
    def post(self, request):
        js_code = request.POST.get("code", '')
        headers = {"Accept": "application/json", }
        get_url = f"https://api.weixin.qq.com/sns/jscode2session?appid=wxc669281d321d4ed1&secret=371945c837b88a952c1883b7c11b3ead&js_code={js_code}&grant_type=authorization_code"
        reql = requests.get(get_url, headers=headers)
        request.user.openid = reql.json()["openid"]
        request.user.save()
        returnDict = {'code': 200, 'message': '获取成功!'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ScanCodeApi(LoginRequiredMixin, View):
    def get(self, request):
        returnDict = {'code': 200, 'message': 'success', 'url': "/personal-center/my_test.html", "type": '1', "real_name": request.user.real_name, "job_number": request.user.job_number, "id": request.user.id}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")